Sergio del Amo Sergio del Amo - 1 year ago 81
Java Question

How to perform string Diffs in Java?

I would need to perform Diffs between Java strings. I would like to be able to rebuild a string from the original string and diff versions. Does anyone has done this in Java? What library do you use?

String a1; // This can be a long text
String a2; // ej. above text with spelling corrections
String a3; // ej. above text with spelling corrections and an additional sentence

Diff diff = new Diff();
String differences_a1_a2 = Diff.getDifferences(a,changed_a);
String differences_a2_a3 = Diff.getDifferences(a,changed_a);
String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3};
String new_a3 =;
a3.equals(new_a3); // this is true

Answer Source

This library seems to do the trick: google-diff-match-patch. It can create a patch string from differences and allow to reapply the patch.

edit: Another solution might be to

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download