java - 比较文件的某些部分

标签 java

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

我想要完成的是读取前 3 行,跳过下一行,将其与下 3 行进行比较,跳过下一行并将其与下 3 行进行比较,然后移动到第二 3 行,并将其与第三组和第四组进行比较,依此类推。所以我想做的是类似

 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

最佳答案

假设文件适合内存,我将使用 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)

关于java - 比较文件的某些部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15562073/

相关文章:

java - 多线程 - 为什么下面的程序表现得如此奇怪?

java - 哈希表的优点

java - 尝试将文件从一个位置复制到另一个位置

java - 我将如何编写一种重新排列牌组中的牌的方法

java - 使用 Eclipse 和 Rserve 从 Java 调用 R 的简单程序

java - 如何将一行 Swing Jtable 设置为 'selected'?

java - Redis 和 Java 在多线程应用中的帮助!

java - 我应该何时以及如何使用 ThreadLocal 变量?

java - Websphere 在运行时工作但在调试时失败

java - 从 2.2.0 spring-boot-maven-plugin 开始创建 2 个 java 进程(可能会导致 CreateProcess error=206)。需要解决方法来修复它