两个文件如何比较差异?可能会想到有文件比对工具,比如Beyond Compare
等
用Java
如何做呢?,今天介绍一下java-diff-utils
java-diff-utils 是基于java
的一种diff
实现
github地址: https://github.com/java-diff-utils/java-diff-utils
github 上有一些案例,此处不再赘述.此处只写一种比对两个文件的差异
- 第一步 pom文件中,引入
jar
依赖
<dependency>
<groupId>io.github.java-diff-utils</groupId>
<artifactId>java-diff-utils</artifactId>
<version>4.5</version>
</dependency>
- 第二步 准备两个差异文件(最好由一个文件复制后对文件进行修改/新增/删除)
- 第三步 编写代码
public static void main(String[] args) throws IOException, DiffException {
File src = new File("/Users/jiabiaoli/Desktop/v0/DruidPooledPreparedStatement.java");
File target = new File("/Users/jiabiaoli/Desktop/v1/DruidPooledPreparedStatement.java");
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;
}
});
}
- 部分运行结果如下
- 2 [ * Copyright 1999-2011 Alibaba Group Holding Ltd.]
+ 2 [ * Copyright 1999-2018 Alibaba Group Holding Ltd.]
- 41 [import com.alibaba.druid.proxy.jdbc.PreparedStatementProxy;]
- 47 [ * @author wenshao<szujobs@hotmail.com>]
+ 46 [ * @author wenshao [szujobs@hotmail.com]]
+ 69 [ private boolean pooled = false;, ]
- 72 [ super(conn, holder.getStatement());, this.stmt = holder.getStatement();]
+ 73 [ super(conn, holder.statement);, this.stmt = holder.statement;]
- 说明
DeltaType
共计有四种类型,分别是EQUAL
,DELETE
,INSERT
,CHANGE
.含义也很好理解分别为相同
,删除
,新增
,修改
delta.getSource()
可以获取源文件的相关信息,delta.getTarget()
可以获取目标文件的相关相关信息,返回值均为Chunk<String>
,新增时delta.getSource()
的信息为空(非null),删除时delta.getTarget()
的信息为空(非null)
chunk.getPosition()+1
则为行号,chunk.getLines()
为对比的文字内容,