这是jgit - git diff based on file extension的后续问题.
我正在尝试将格式化的差异添加到 List<String>
但如果我尝试使用相同的 DiffFormatter
如下所示,之前的条目将附加到下一个条目。
List<String> changes = new LinkedList<>();
try (OutputStream outputStream = new ByteArrayOutputStream();
DiffFormatter diffFormatter = new DiffFormatter(outputStream)) {
diffFormatter.setRepository(git1.getRepository());
TreeFilter treeFilter = PathSuffixFilter.create(".txt");
diffFormatter.setPathFilter(treeFilter);
List<DiffEntry> entries = diffFormatter.scan(newTree, oldTree);
for (DiffEntry diffEntry : entries) {
diffFormatter.format(diffEntry);
changes.add(outputStream.toString());
diffFormatter.flush();
}
}
因此我被迫创建一个 DIffFormatter
对于每个差异条目。
有没有更好的方法来创建List<String> from List<DiffEntry>
无需创建新的 DiffFormatter
每次?
最佳答案
前面的条目被附加的原因是使用了相同的输出流。调用 outputStream.toString()
返回到目前为止已写入的所有字节的字符串。因此,在 for 循环中每次调用 toString
都会返回所有先前创建的差异,加上当前的差异。
我看到了解决这个问题的两种方法:
在 for 循环中为每个 diff 条目使用单独的
DiffFormatter
。实现自定义
OutputStream
,允许丢弃以前写入的内容。
关于java - JGit - 如何重用 DiffFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54019259/