本文介绍了想用java找到两个文本文件之间的内容差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个文本文件,
- a.txt
- b.txt
每个文本文件都包含一些文件路径。 b.txt
包含比 a.txt
更多的文件路径。我想确定添加哪些路径以及从 a.txt
中删除哪些路径,以便它对应于 b.txt 。
Each text files contains some file paths.
b.txt
contains some more file paths than a.txt
. I would like to determine which paths are added and which are removed from a.txt
so that it corresponds to paths in b.txt
.
例如,
abc.txt包含
E:\Users\Documents\hello\a.properties
E:\Users\Documents\hello\b.properties
E:\Users\Documents\hello\c.properties
和xyz.txt包含
E:\Users\Documents\hello\a.properties
E:\Users\Documents\hello\c.properties
E:\Users\Documents\hello\g.properties
E:\Users\Documents\hello\h.properties
现在如何找到添加的g.prop和h.prop和b .prop被删除了?
Now how to find that g.prop and h.prop are added and b.prop is removed?
有人可以解释一下它是如何完成的吗?我只能找到如何检查相同的内容。
Could anyone explain how it is done? I could only find how to check for identical contents.
推荐答案
以下代码将满足您的目的,无论文件的内容如何。
The below code will serve your purpose irrespective of the content of the file.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public Test(){
System.out.println("Test.Test()");
}
public static void main(String[] args) throws Exception {
BufferedReader br1 = null;
BufferedReader br2 = null;
String sCurrentLine;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
br1 = new BufferedReader(new FileReader("test.txt"));
br2 = new BufferedReader(new FileReader("test2.txt"));
while ((sCurrentLine = br1.readLine()) != null) {
list1.add(sCurrentLine);
}
while ((sCurrentLine = br2.readLine()) != null) {
list2.add(sCurrentLine);
}
List<String> tmpList = new ArrayList<String>(list1);
tmpList.removeAll(list2);
System.out.println("content from test.txt which is not there in test2.txt");
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test.txt which is not there in test2.txt
}
System.out.println("content from test2.txt which is not there in test.txt");
tmpList = list2;
tmpList.removeAll(list1);
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test2.txt which is not there in test.txt
}
}
}
这篇关于想用java找到两个文本文件之间的内容差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!