两个文件如何比较差异?可能会想到有文件比对工具,比如Beyond Compare
等
用Java
如何做呢?,今天介绍一下java-diff-utils
java-diff-utils 是基于java
的一种diff
实现
github地址: https://github.com/java-diff-utils/java-diff-utils
github 上有一些案例,此处不再赘述.此处只写一种比对两个文件的差异
jar依赖
<dependency> <groupId>io.github.java-diff-utils</groupId> <artifactId>java-diff-utils</artifactId> <version>4.5</version> </dependency>
package com.XXXX; import com.github.difflib.DiffUtils; import com.github.difflib.algorithm.DiffException; import com.github.difflib.patch.AbstractDelta; import com.github.difflib.patch.Chunk; import com.github.difflib.patch.Patch; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; class ModuleEventWatcher { public static void main(String[] args) throws IOException, DiffException { File src = new File("D:/MS/log1.log"); File target = new File("D:/MS/log2.log"); List<String> original = IOUtils.readLines(new FileInputStream(src), "UTF-8"); List<String> revised = IOUtils.readLines(new FileInputStream(target), "UTF-8"); Patch<String> diff = DiffUtils.diff(original, revised); List<AbstractDelta<String>> deltas = diff.getDeltas(); deltas.forEach(delta -> { switch (delta.getType()) { case INSERT: //新增 Chunk<String> insert = delta.getTarget(); int position = insert.getPosition(); System.out.println("+ " + (position + 1) + " " + insert.getLines()); break; case CHANGE: //修改 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: //删除 Chunk<String> delete = delta.getSource(); System.out.println("- " + (delete.getPosition() + 1) + " " + delete.getLines()); break; case EQUAL: // System.out.println("无变化"); break; } }); } }
运行结果
- 说明
DeltaType
共计有四种类型,分别是EQUAL
,DELETE
,INSERT
,CHANGE
.含义也很好理解分别为相同
,删除
,新增
,修改
delta.getSource()
可以获取源文件的相关信息,delta.getTarget()
可以获取目标文件的相关相关信息,返回值均为Chunk<String>
,新增时delta.getSource()
的信息为空(非null),删除时delta.getTarget()
的信息为空(非null)
chunk.getPosition()+1
则为行号,chunk.getLines()
为对比的文字内容,