Friday, January 13, 2012

Java : Compare two files

Other day I was required to compare contents of two files in Java. Lets see how to compare two txt files in Java?

I was wondering if there is a Java APIs for Text file comparison, which will compare contents of two txt files using java program.

Basically the java program should mimc the behaviour of diff command of LINUX. diff is a file comparison utility that outputs the differences between two files. It is typically used to show the changes between one version of a file and a former version of the same file. Diff displays the changes made per line for text files.

Output of the java program should give same as result produced by diff command. I got many codes on net but they were not working as expected. Latter i got an idea, why not we can use diff command in our java program to produce the same result. But diff command works for LINUX, what is equivalent for Windows? Well i found COMP or FC are equivalent windows command for diff in LINUX. So with the help of these commands we can build a JAVA program which will compare contents of two txt files.

Lets see the code.

No need to add any jar file, directly you can run this code and see the output.

/* */


public class CompareFiles {

    public void compare(String file1,String file2) {
        //For Windows
        runSystemCommand("fc /N \""+file1+"\" \""+file2+"\"");
        //For UNIX / LINUX
        //runSystemCommand("diff "+file1+" "+file2);
    public void runSystemCommand(String command) {
        try {
            Process proc = Runtime.getRuntime().exec(command);
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader errorStream = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String strLn = "";
            // reading output stream of the command
            while ((strLn = inputStream.readLine()) != null) {
            // reading errors of the command (if any)
            while ((strLn = errorStream.readLine()) != null) {
        } catch (Exception e) {
    public static void main(String[] args) {
        CompareFiles cf = new CompareFiles();