JFileChooser 到 select 多个文本文件并比较它们

JFileChooser to select multiple text files and compare them

我想使用 JFileChooser select 多个文本文件,然后比较它们。 选择多个文件的代码如下

    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(true);
    Component frame = null;
    chooser.showOpenDialog(frame);
    File[] files = chooser.getSelectedFiles();

如何使用文件句柄比较多个文件。是否可以使用此方法比较多个文本文件。 我有多个文本文件,我想检查所有文件的内容是否匹配。如果内容完全相同,我会看到 MATCH,如果文本文件不同,我会看到 FAIL 以及内容差异。 非常感谢您的帮助

使用FileUtils

示例:

for(int i=0; i<files.length-1; i++) 
    for(int j=i+1; j<files.length; j++)
        if(FileUtils.contentEquals(files[i], files[j]))
            System.out.println("file #" + i + " and file #" + j + " are identical.";
        else
            System.out.println("file #" + i + " and file #" + j + " are different.";

example#2 - 不使用外部库 您可以使用 this 答案中描述的技术。

for(int i=0; i<files.length-1; i++) {
    for(int j=i+1; j<files.length; j++) {
        byte[] f1 = Files.readAllBytes(files[i]);
        byte[] f2 = Files.readAllBytes(files[j]);

        if (Arrays.equals(f1, f2))
            System.out.println("file #" + i + " and file #" + j + " are identical.";
        else
            System.out.println("file #" + i + " and file #" + j + " are different.";
    }
}

P.S.: 由于你的问题中没有提到,我这里假设你想比较两个文件的内容并判断它们是否相等。