Baeldung

Java, Spring and Web Development tutorials

 

Guide to Java Diff Utils
2025-06-06 08:13 UTC by Sagar Verma

1. Overview

In modern software development, tracking and visualizing changes between different versions of files or content is vital. Whether we’re building a version control system, a collaborative editor, or a code review tool, efficiently comparing content is essential. One of the popular ways to achieve this in Java is using Java Diff Utils.

This tutorial demonstrates how to use the Java Diff Utils library to perform various tasks, including comparing text content line-by-line, generating unified diffs, applying patches to restore or modify content, and building side-by-side diff views.

2. Understanding Java Diff Utils and Key Benefits

Java Diff Utils is a lightweight and powerful library for computing differences between text data. It supports both character-level and line-level comparisons and generates unified diff outputs.

It’s commonly used in version control systems and applies patches to transform one version of data into another.  This utility provides various classes and methods that simplify the comparison process.

The following are the key benefits of Java Diff Utils:

  • Simplicity: Offers a clean and intuitive API with static utility methods
  • Extensibility: Easily integrates with Spring Boot services and controllers
  • Cross-platform: Compatible with any operating system that supports Java
  • Open Source: Free to use and modify under the Apache License

These capabilities make Java Diff Utils an ideal choice for reliable text comparison features in Java applications.

3. Setting up Diff Utils

Before diving in, we’ll set up a simple Spring Boot application with Maven through Spring Initializr.

While Java Diff Utils can be used in plain Java by manually managing JARs and classpaths, Spring Boot with Maven simplifies this by handling all dependencies automatically through pom.xml. This approach not only reduces setup time but also ensures better portability and consistency across environments. Maven takes care of downloading, managing, and resolving all required artifacts.

To get started, we add the Java Diff Utils dependency to our pom.xml file:

<dependency>
    <groupId>io.github.java-diff-utils</groupId>
    <artifactId>java-diff-utils</artifactId>
    <version>4.12</version>
</dependency>

With this setup, Maven ensures the correct version of Java Diff Utils is available during both compilation and runtime.

Now, we can start using the core classes like DiffUtils, Patch, and UnifiedDiffUtils directly. These classes are all utility-based, meaning no explicit instance creation is required. This design allows for straightforward integration into service classes, controller layers, or standalone Java components.

4. Using Diff Utils in Java

In this section, we’ll walk through building some basic components to learn how to use the Java Diff Utils library in various scenarios. We’ll explore several core use cases and look at implementations for comparing text content using various strategies within our Java application. We’ll create implementations for comparing content, generating diffs, applying patches, and viewing changes side-by-side using the Java Diff Utils library.

Let’s explore the core use cases with implementations further.

4.1. Comparing Lists of Strings

Let’s create a utility class named TextComparatorUtil that compares two lists of strings and generates a patch representing their differences. This utility class streamlines the process of identifying changes between text versions:

class TextComparatorUtil {
    public static Patch<String> compare(List<String> original, List<String> revised) {
        return DiffUtils.diff(original, revised);
    }
}

Let’s verify that TextComparatorUtil correctly detects and reports changes between two lists of strings:

@Test
void givenDifferentLines_whenCompared_thenDetectsChanges() {
    var original = List.of("A", "B", "C");
    var revised = List.of("A", "B", "D");
    var patch = TextComparatorUtil.compare(original, revised);
    assertEquals(1, patch.getDeltas().size());
    assertEquals("C", patch.getDeltas().get(0).getSource().getLines().get(0));
    assertEquals("D", patch.getDeltas().get(0).getTarget().getLines().get(0));
}

4.2. Generating Unified Diffs

Next, let’s create a class UnifiedDiffGeneratorUtil that generates a unified diff between two lists of strings, representing the differences in a standard patch format:

class UnifiedDiffGeneratorUtil {
    public static List<String> generate(List<String> original, List<String> revised, String fileName) {
        var patch = DiffUtils.diff(original, revised);
        return UnifiedDiffUtils.generateUnifiedDiff(fileName, fileName + ".new", original, patch, 3);
    }
}

When we specify the original and revised content along with a file name, it produces a unified diff output suitable for code reviews or version control systems.

Let’s write a Junit test to ensure that the UnifiedDiffGeneratorUtil correctly highlights modified lines in the unified diff output:

@Test
void givenModifiedText_whenUnifiedDiffGenerated_thenContainsExpectedChanges() {
    var original = List.of("x", "y", "z");
    var revised = List.of("x", "y-modified", "z");
    var diff = UnifiedDiffGeneratorUtil.generate(original, revised, "test.txt");
    assertTrue(diff.stream().anyMatch(line -> line.contains("-y")));
    assertTrue(diff.stream().anyMatch(line -> line.contains("+y-modified")));
}

4.3. Applying Patches

Next, let’s write a class PatchUtil that generates and applies a patch to update the original content. It transforms the original list of strings into the revised version:

class PatchUtil {
    public static List<String> apply(List<String> original, List<String> revised) throws PatchFailedException {
        var patch = DiffUtils.diff(original, revised);
        return DiffUtils.patch(original, patch);
    }
}

It first computes the differences, then applies the resulting patch to update the original content.

Now, we’ll verify that PatchUtil correctly applies a patch so that the original list matches the revised list:

@Test
void givenPatch_whenApplied_thenMatchesRevised() throws PatchFailedException {
    var original = List.of("alpha", "beta", "gamma");
    var revised = List.of("alpha", "beta-updated", "gamma");
    var result = PatchUtil.apply(original, revised);
    assertEquals(revised, result);
}

4.4. Building a Side-by-Side Diff View

Finally, let’s create a SideBySideViewUtil class that provides a method to display differences between two lists of strings in a readable format:

public class SideBySideViewUtil {
    private static final Logger logger = Logger.getLogger(SideBySideViewUtil.class.getName());
    public static void display(List<String> original, List<String> revised)
    {
        var patch = DiffUtils.diff(original, revised);
        patch.getDeltas().forEach(delta -> {
            logger.log(Level.INFO,"Change: " + delta.getType());
            logger.log(Level.INFO,"Original: " + delta.getSource().getLines());
            logger.log(Level.INFO,"Revised: " + delta.getTarget().getLines());
        });
    }
}

It identifies each change and prints the type of change along with the corresponding lines from both the original and revised versions. This makes it easier to quickly visualize and understand modifications between text versions.

While Java Diff Utils doesn’t directly generate HTML views, it exposes the source and target lines from deltas. These can be used to build custom visual representations, which can then be translated into formatted HTML for web-based diff viewers.

This test verifies that the SideBySideViewUtil.display() method executes without errors when comparing two different lists of strings:

@Test
void givenDifferentLists_whenDisplayCalled_thenNoExceptionThrown() {
    List<String> original = List.of("line1", "line2", "line3");
    List<String> revised = List.of("line1", "line2-modified", "line3", "line4");
    SideBySideViewUtil.display(original, revised);
}

5. Conclusion

This article explored Java Diff Utils and its various features. Java Diff Utils provides a flexible, open-source solution for comparing text data in Java applications. From basic line-by-line diffs to full unified diff generation and patching capabilities, it serves as a foundational tool for building robust version control or change-tracking systems.

With minimal setup and highly readable output, Java Diff Utils is a must-have for developers working with versioned data, collaborative editing tools, or file monitoring systems.

As always, the code for these examples is available over on GitHub.

The post Guide to Java Diff Utils first appeared on Baeldung.
       

 

Content mobilized by FeedBlitz RSS Services, the premium FeedBurner alternative.