1

I have a question that has been eluding me for the whole day. I want to read part of a file and compare it to other parts of same file. if I can get some kind of logic on how to collect the first set of lines and compare it with the other sets and then move to the next set and compare with the remaining until I compare every set with each other..

what I want to accomplish is this read the first 3 lines skip the next compare it with the next 3 line, skip the next and compare it with the next 3 line and after that move to the 2nd 3 lines and compare that with the 3rd set and 4th set and so on. So what am trying to do is something like

 for{ int i=0; i < file.lenght; i++

     for {int j=0; j=i+1; i++{

   }}

but for a txt file

SAMPLE FILE

 this is the way to go
 this is not really it
 what did they say it was
 laughing hahahahahahahaa
 are we on the right path
 this is not really it
 what did they say it was
 smiling hahahahahahahaha
 they are way behind 
 tell me how to get therr
 home here we come
 hahahahahahahaha they laught
 are we on the right path
 this is not really it
 what did they say it was
4

1 に答える 1

1

ファイルがメモリに収まると仮定すると、Files.readAllLines(path,charset) (Java 7) を使用してすべての行を List に読み込み、List で比較を行います。

ファイルが大きすぎる場合は、メソッドを作成します

List<String> readLines(Scanner sc, int nLines) {
    List<String> list = new ArrayList<>();
    for (int i = 0; i < nLines; i++) {
        list.add(sc.nextLine());
    }
    return list;
}

それを使用して、ファイルの一部を読み取り/スキップします

Scanner sc = new Scanner(new File("path"));
List<String> list1 = readLines(sc, 3);
readLines(sc, 1);
List<String> list2 = readLines(sc, 3);
boolean res = list1.equals(list2)
于 2013-03-22T03:24:37.880 に答える