google-diff-match-patch
测试代码:
String aa = "DiffMatchPatch dmp = new DiffMatchPatch();";
String bb = "DiffMatchPatch String = JSONObject DiffMatchPatch();";
DiffMatchPatch dmp = new DiffMatchPatch();
LinkedList<DiffMatchPatch.Diff> diff = dmp.diff_main(aa,bb,false);
diff.forEach(diff1 -> {
System.out.println(JSONObject.toJSONString(diff1));
});
结果:
结果是list,并且是顺序往下,
代码:
LinkedList<DiffMatchPatch.Diff> diffs = dmp.diff_main(lastOld,last,false); //差异结果
List<Map<String, String>> maps = Lists.newArrayList(); //存放的结果集
diffs.forEach(diff -> {
Map<String, String> map = Maps.newHashMap();
if(DiffMatchPatch.Operation.EQUAL.equals(diff.operation)){ //无操作
map.put("key",DiffMatchPatch.Operation.EQUAL.name());
map.put("value",diff.text);
}else if(DiffMatchPatch.Operation.DELETE.equals(diff.operation)){ //删除
map.put("key",DiffMatchPatch.Operation.DELETE.name());
map.put("value",diff.text);
}else if(DiffMatchPatch.Operation.INSERT.equals(diff.operation)){ //插入
map.put("key",DiffMatchPatch.Operation.INSERT.name());
map.put("value",diff.text);
}
maps.add(map);
});
item.setContents(maps);
freemarker 出引用结果,按顺序拼接:
<#list reviewItem.contents as map>
<#if map["key"] == "EQUAL">
<w:r>
<w:rPr>
<w:rFonts w:ascii="仿宋_GB2312" w:hAnsi="仿宋_GB2312" w:cs="仿宋_GB2312" w:hint="eastAsia"/>
<w:lang w:bidi="ar"/>
</w:rPr>
<w:t xml:space="preserve">${map["value"]?replace('\r','<w:br/>')}</w:t>
</w:r>
</#if>
<#if map["key"] == "INSERT">
<w:r w:rsidRPr="00262298">
<w:rPr>
<w:rFonts w:ascii="仿宋_GB2312" w:hAnsi="仿宋_GB2312" w:cs="仿宋_GB2312" w:hint="eastAsia"/>
<w:color w:val="FF0000"/>
<w:u w:val="single"/>
<w:lang w:bidi="ar"/>
</w:rPr>
<w:t>${map["value"]?replace('\r','<w:br/>')}</w:t>
</w:r>
</#if>
<#if map["key"] == "DELETE">
<w:r w:rsidRPr="00262298">
<w:rPr>
<w:rFonts w:ascii="仿宋_GB2312" w:hAnsi="仿宋_GB2312" w:cs="仿宋_GB2312" w:hint="eastAsia"/>
<w:strike/>
<w:color w:val="1A45FA"/>
<w:lang w:bidi="ar"/>
</w:rPr>
<w:t>${map["value"]?replace('\r','<w:br/>')}</w:t>
</w:r>
</#if>
</#list>
实际结果展示(转换了pdf,因为没有字体所以是乱码):
maven引用:
<dependency>
<groupId>org.bitbucket.cowwoc</groupId>
<artifactId>diff-match-patch</artifactId>
<scope>1.2</scope>
</dependency>
实际使用可以吧代码放项目。不需要maven去引用,