Java 如何Diff文件

两个文件如何比较差异?可能会想到有文件比对工具,比如Beyond Compare
Java如何做呢?,今天介绍一下java-diff-utils

java-diff-utils 是基于java的一种diff实现
github地址: https://github.com/java-diff-utils/java-diff-utils

github 上有一些案例,此处不再赘述.此处只写一种比对两个文件的差异

  • 第一步 pom文件中,引入jar依赖

  io.github.java-diff-utils
  java-diff-utils
  4.5

  • 第二步 准备两个差异文件(最好由一个文件复制后对文件进行修改/新增/删除)
  • 第三步 编写代码
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 original = IOUtils.readLines(new FileInputStream(src), "UTF-8");
        List revised = IOUtils.readLines(new FileInputStream(target), "UTF-8");
        Patch diff = DiffUtils.diff(original, revised);
        List> deltas = diff.getDeltas();
        deltas.forEach(delta -> {
            switch (delta.getType()) {
                case INSERT:
                    //新增
                    Chunk insert = delta.getTarget();
                    int position = insert.getPosition();
                    System.out.println("+ " + (position + 1) + " " + insert.getLines());
                    break;
                case CHANGE:
                    //修改
                    Chunk source = delta.getSource();
                    Chunk target1 = delta.getTarget();
                    System.out.println("\n- " + (source.getPosition() + 1) + " " + source.getLines() + "\n+ " + "" + (target1.getPosition() + 1) + " " + target1.getLines());
                    break;
                case DELETE:
                    //删除
                    Chunk 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]
+ 46 [ * @author wenshao [[email protected]]]
+ 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,新增时delta.getSource()的信息为空(非null),删除时delta.getTarget()的信息为空(非null)

chunk.getPosition()+1则为行号,chunk.getLines()为对比的文字内容,

你可能感兴趣的:(Java 如何Diff文件)