如何比较两个文本文件的内容并返回“相同内容”或“不同内容”?

时间:2009-10-02 16:13:48

标签: java

我的Java应用程序需要能够比较文件系统中的两个不同文件,并确定它们的二进制内容是否相同。

这是我目前的代码:

package utils;
import java.io.*;

class compare { 
    public static void main(String args[]) throws IOException {
        FileInputStream file1 = new InputStream(args[0]);
        FileInputStream file2 = new InputStream(args[1]);

        try {
            if(args.length != 2)
                throw (new RuntimeException("Usage : java compare <filetoread> <filetoread>"));
            while (true) {
                int a = file1.read();
                int b = file2.read();
                if (a==-1) { 
                    System.out.println("Both the files have same content"); 
                }
                else{
                    System.out.println("Contents are different");
                }
            }
        }
        catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}

有关如何正确使用比较功能的任何提示或建议将不胜感激。

3 个答案:

答案 0 :(得分:7)

最简单的方法是将内容读入两个字符串,例如

  FileInputStream fin =  new FileInputStream(args[i]);
  BufferedReader myInput = new BufferedReader(new InputStreamReader(fin));
  StringBuilder sb = new StringBuilder();
  while ((thisLine = myInput.readLine()) != null) {  
             sb.append(thisLine);
  }

,并对这些内容执行.equals()。您是否需要更复杂的差异功能?

答案 1 :(得分:3)

import java.io.*;

public class Testing {
public static void main(String[] args) throws java.io.IOException {

    BufferedReader bfr2 = new BufferedReader(new InputStreamReader(
            System.in));
    String s1 = "";
    String s2 = "", s3 = "", s4 = "";
    String y = "", z = "";

    File file1 = new File("args[0]");
    File file2 = new File("args[1]");

    BufferedReader bfr = new BufferedReader(new FileReader(file1));
    BufferedReader bfr1 = new BufferedReader(new FileReader(file2));

    while ((z = bfr1.readLine()) != null)
        s3 += z;

    while ((y = bfr.readLine()) != null)
        s1 += y;

    System.out.println();

    System.out.println(s3);

    if (s3.equals(s1)) {
        System.out.println("Content of both files are same");
    } else {

        System.out.println("Content of both files are not same");
    }
}
}

答案 2 :(得分:2)

读取文件的内容并使用MessageDigest类创建每个文件内容的MD5哈希值。然后比较两个哈希值。这样做的好处就是可以处理二进制文件。