Home > Software Development > How to Use GIT Java APIs to Diff Two Different Files

How to Use GIT Java APIs to Diff Two Different Files

February 11th, 2013 Leave a comment Go to comments

In my previous post, I introduced a sample showing how to use JGIT Java APIs to diff two versions of a same file in repository. The JGIT Java APIs can do more than that โ€“ it can actually diff two text files that are not even controlled by GIT.
Here is a short sample code on how to do this. Again, itโ€™s not the main use case for the JGIT APIs. After all, itโ€™s mainly for GIT source control system itself. You can always use other diff APIs for this purpose. However, if you already have JGIT included, this can be handy.

/**Copyright Steve Jin 2013 */
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.EditList;
import org.eclipse.jgit.diff.HistogramDiff;
import org.eclipse.jgit.diff.RawText;
import org.eclipse.jgit.diff.RawTextComparator;

public class RawDiff
{
  public static void main(String[] args) throws Exception
  {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    
    try 
    {
      RawText rt1 = new RawText(new File("C:\\temp\\twofiles\\file1.txt"));
      RawText rt2 = new RawText(new File("C:\\temp\\twofiles\\file2.txt"));
      EditList diffList = new EditList();
      diffList.addAll(new HistogramDiff().diff(RawTextComparator.DEFAULT, rt1, rt2));
      new DiffFormatter(out).format(diffList, rt1, rt2);
    } catch (IOException e)
    {
      e.printStackTrace();
    }
    System.out.println(out.toString());
  }
}

The output of the program is like this:

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

HTML5 App
@@ -1,3 +1,4 @@
 This is doublecloud.org
 it just rocks!
+Yes
 what an interesting work
\ No newline at end of file

Categories: Software Development Tags: ,
  1. lilo
    July 11th, 2013 at 10:11 | #1

    Thanks a lot guy! ๐Ÿ˜€

    Really needed this.

  1. No trackbacks yet.