比较文件的某些部分

时间:2013-03-22 03:13:14

标签: java

我有一个问题,一整天都在躲避我。我想读取文件的一部分并将其与同一文件的其他部分进行比较。如果我可以得到一些关于如何收集第一组线并将其与其他组进行比较的逻辑,然后移动到下一组并与其余组进行比较,直到我将每组相互比较..

我想要完成的是读取前3行,然后跳过下一行与下3行比较,跳过下一行并将其与下一行3进行比较,之后移动到第3行并将其与之比较第3组和第4组等等。所以我想做的就是

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

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

   }}

但是对于txt文件

样本文件

 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

1 个答案:

答案 0 :(得分:1)

假设文件适合内存,我会将所有行读入List with Files.readAllLines(path,charset)(Java 7),然后在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)
相关问题