How to merge source code files


GroupDocs.Comparison for Java provides an ability to merge source code files by using the ComparisonAction properties:

The following are the steps to apply/reject changes to resultant file.

Example of merge source code file by using GroupDocs.Comparison


For example, you need to compare and merge several versions of source code files and you need to accept or discard changes made by different persons.

The differences show that two methods are written in the source.cs file: AddNumbers and Sum.

If you did not use ComparisonAction, then in the resulting file, all changes will be committed, and these methods will be removed, but if you need to control the merging of files, the ComparisonAction property will help you with this.

Example of using ComparisonAction


The following code samples demonstrate how to merge two source code files.

try (Comparer comparer = new Comparer(sourcePath)) {
    comparer.add(targetPath);
    final Path resultPath = comparer.compare(RESULT_PATH);

    ChangeInfo[] changes = comparer.getChanges();
    for (int i = 0; i < 10; i++) {
        changes[i].setComparisonAction(ComparisonAction.ACCEPT);
    }

    for (int i = 10; i < changes.length; i++) {
    	changes[i].setComparisonAction(ComparisonAction.REJECT);
    }

    comparer.applyChanges(resultPath, new ApplyChangeOptions(changes));
}

The result of merging files


As a result, we get a merged source code file where the deleted elements are marked in red, the added – in blue, and the modified – in green.

Also, you will receive a file in HTML format with changed places in the code.

Result source code fileResult HTML file

As you can see from the resulting files, only one of the two methods was removed.

More resources


GitHub Examples

You may easily run the code above and see the feature in action in our GitHub examples:

Free Online App

Along with full-featured Java library we provide simple, but powerful free Apps. You are welcome to compare your DOC or DOCX, XLS or XLSX, PPT or PPTX, PDF, EML, EMLX, MSGand other documents with free to use online GroupDocs Comparison App.