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<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 回答