比较Java中的两个文件

时间:2018-03-05 16:46:44

标签: java

我是Java的新手,我编写的代码用于比较Java中的两个数据文件,但这只适用于1行,不适用于所有行或整个文件。以下是我的代码。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CompareTextFiles {

    public static void main(String[] args) throws IOException {
        BufferedReader reader1 = new BufferedReader(new FileReader("D:/Data/file1.docx"));
        BufferedReader reader2 = new BufferedReader(new FileReader("D:/Data/file2.docx"));
        String line1 = reader1.readLine();
        String line2 = reader2.readLine();
        boolean areEqual = true;
        int lineNum = 1;
        while (line1 != null || line2 != null) {
            if (line1 == null || line2 == null) {
                areEqual = false;
                break;
            } else if (!line1.equalsIgnoreCase(line2)) {
                areEqual = false;
                break;
            }
            line1 = reader1.readLine();
            line2 = reader2.readLine();
            lineNum++;
        }
        if (areEqual) {
            System.out.println("Two files have same content.");
        } else {
            System.out.println("Two files have different content. They differ at line " + lineNum);
            System.out.println("File1 has " + line1 + " and File2 has " + line2 + " at line " + lineNum);
        }
        reader1.close();
        reader2.close();
    }
}

1 个答案:

答案 0 :(得分:0)

使用fileInputStream然后使用两个嵌套的for循环O(n ^ 2),我知道,就目前而言。 然后对你的流对象使用.hasNext()< - boolean,如果为true,则使用.next()逐行检查