← Back to Home

1diff-java

Java implementation of text diff library based on Myers Diff Algorithm. This is a Java port of the 1diff-ts JavaScript library.

Features

Installation

Maven

Add the following dependency to your pom.xml:

<dependency>
    <groupId>io.github.daichangya</groupId>
    <artifactId>1diff-java</artifactId>
    <version>1.0.0</version>
</dependency>

Quick Start

Character-level Diff

import diff.io.github.daichangya.CharacterDiff;
import model.io.github.daichangya.ChangeObject;
import java.util.List;

List<ChangeObject<String>> changes = 
    CharacterDiff.diffChars("beep boop", "beep boob blah");

for (ChangeObject<String> change : changes) {
    if (change.isAdded()) {
        System.out.println("+ " + change.getValue());
    } else if (change.isRemoved()) {
        System.out.println("- " + change.getValue());
    } else {
        System.out.println("  " + change.getValue());
    }
}

Line-level Diff

import diff.io.github.daichangya.LineDiff;
import model.io.github.daichangya.DiffOptions;

String oldText = "line1\nline2\nline3";
String newText = "line1\nline2 modified\nline3";

List<ChangeObject<String>> changes = 
    LineDiff.diffLines(oldText, newText);

// With options
DiffOptions options = DiffOptions.builder()
    .ignoreWhitespace(true)
    .stripTrailingCr(true)
    .build();
List<ChangeObject<String>> changes2 = 
    LineDiff.diffLines(oldText, newText, options);

Word-level Diff

import diff.io.github.daichangya.WordDiff;

String oldText = "hello world";
String newText = "hello beautiful world";

List<ChangeObject<String>> changes = 
    WordDiff.diffWords(oldText, newText);

JSON Object Diff

import diff.io.github.daichangya.JsonDiff;
import java.util.Map;

Map<String, Object> oldObj = Map.of("name", "John", "age", 30);
Map<String, Object> newObj = Map.of("name", "John", "age", 31);

List<ChangeObject<String>> changes = 
    JsonDiff.diffJson(oldObj, newObj);

Patch Functionality

Create Patch

import patch.io.github.daichangya.PatchCreator;

String oldText = "line1\nline2\nline3";
String newText = "line1\nline2 modified\nline3";

// Create unified diff format patch
String patch = PatchCreator.createPatch("test.txt", oldText, newText);
System.out.println(patch);

Apply Patch

import patch.io.github.daichangya.PatchApplier;

String result = PatchApplier.applyPatch(oldText, patch);
System.out.println(result);

API Documentation

Diff Classes

All diff classes inherit from the Diff<T> base class, implementing the Myers Diff algorithm.

ChangeObject

Represents a change unit in the diff:

Resources

License

This project is licensed under BSD-3-Clause, consistent with the original 1diff-ts project.

Author

daichangya