<dependency>
<groupId>io.github.java-diff-utils</groupId>
<artifactId>java-diff-utils</artifactId>
<version>4.12</version>
</dependency>
官方文档api
List<String> original = Arrays.asList("This is a test senctence." +
"\r\nThis is a test for diffutils");
//对比文件
List<String> revised = Arrays.asList("This is a test senctence." +
"\r\nThis is a test for diffutils1");
//两文件的不同点
Patch<String> patch = DiffUtils.diff(original, revised);
System.out.println(patch);
List<AbstractDelta<String>> deltas = patch.getDeltas();
deltas.forEach(delta -> {
System.out.println(delta.getType());
switch (delta.getType()) {
case INSERT:
//新增
System.out.println("新增");
Chunk<String> insert = delta.getTarget();
int position = insert.getPosition();
System.out.println("+ " + (position + 1) + " " + insert.getLines());
break;
case CHANGE:
//修改
System.out.println("修改");
Chunk<String> source = delta.getSource();
Chunk<String> target1 = delta.getTarget();
System.out.println("\n- " + (source.getPosition() + 1) + " " + source.getLines() + "\n+ " + "" + (target1.getPosition() + 1) + " " + target1.getLines());
break;
case DELETE:
//删除
System.out.println("删除");
Chunk<String> delete = delta.getSource();
System.out.println("- " + (delete.getPosition() + 1) + " " + delete.getLines());
break;
case EQUAL:
System.out.println("无变化");
break;
}
});
输出
Patch{deltas=[[ChangeDelta, position: 0, lines: [This is a test senctence.
This is a test for diffutils] to [This is a test senctence.
This is a test for diffutils1]]]}
CHANGE
修改
- 1 [This is a test senctence.
This is a test for diffutils]
+ 1 [This is a test senctence.
This is a test for diffutils1]
进程已结束,退出代码为 0
List<String> original = Arrays.asList("This is a test senctence." +
"\r\nThis is a test for diffutils");
//对比文件
List<String> revised = Arrays.asList("This is a test senctence." +
"\r\nThis is a test for diffutils1");
//两文件的不同点
Patch<String> patch = DiffUtils.diff(original, revised);
//生成统一的差异格式
List<String> unifiedDiff = UnifiedDiffUtils.generateUnifiedDiff("test1.txt", "test2.txt", original, patch, 0);
System.out.println(unifiedDiff);
输出
[--- test1.txt, +++ test2.txt, @@ -1,1 +1,1 @@, -This is a test senctence.
This is a test for diffutils, +This is a test senctence.
This is a test for diffutils1]
进程已结束,退出代码为 0