我需要比较2个文本文件(MasterCopy.txt
和ClientCopy.txt)
。我想获取ClientCopy.txt中缺少的字符串列表。还需要获取字符串列表这是过度的。
MasterCopy.txt的内容
ClientCopy.txt的内容
我想得到这些结果
缺少:
过剩:
答案 0 :(得分:0)
我想到的两个想法是获得两个文件的差异:
https://code.google.com/p/java-diff-utils/
来自他们的维基
任务1:计算文件之间的差异并打印其增量 解决方案:
import difflib.*; public class BasicJavaApp_Task1 { // Helper method for get the file content private static List<String> fileToLines(String filename) { List<String> lines = new LinkedList<String>(); String line = ""; try { BufferedReader in = new BufferedReader(new FileReader(filename)); while ((line = in.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); } return lines; } public static void main(String[] args) { List<String> original = fileToLines("originalFile.txt"); List<String> revised = fileToLines("revisedFile.xt"); // Compute diff. Get the Patch object. Patch is the container for computed deltas. Patch patch = DiffUtils.diff(original, revised); for (Delta delta: patch.getDeltas()) { System.out.println(delta); } } }
或使用HashSet:
http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
修改@ Nic的使用HashSet的答案:
Scanner s = new Scanner(new File(“MasterCopy.txt”));
HashSet<String> masterlist = new HashSet<String>();
while (s.hasNext()){
masterlist.put(s.next());
}
s.close();
s = new Scanner(new File(“ClientCopy.txt”));
HashSet<String> clientlist = new HashSet<String>();
while (s.hasNext()){
clientlist.put(s.next());
}
s.close();
//Do the comparison
ArrayList<String> missing = new ArrayList<String>();
ArrayList<String> excess = new ArrayList<String>();
//Check for missing or excess
for(String line : masterlist){
if(clientlist.get(line) == null) missing.add(line);
}
for(String line : clientlist){
if(masterlist.get(line) == null) excess.add(line);
}
答案 1 :(得分:0)
如果执行时间不是一个很重要的因素,你可以这样做,假设你只是比较每一行:
//Get the files into lists
Scanner s = new Scanner(new File(“MasterCopy.txt”));
HashSet<String> masterlist = new HashSet<String>();
while (s.hasNext()){
masterlist.add(s.next());
}
s.close();
s = new Scanner(new File(“ClientCopy.txt”));
HashSet<String> clientlist = new HashSet<String>();
while (s.hasNext()){
clientlist.add(s.next());
}
s.close();
//Do the comparison
HashSet<String> missing = new HashSet<String>();
HashSet<String> excess = new HashSet<String>();
//Check for missing or excess
for(String s : masterlist){
if(!clientlist.contains(s)) missing.add(s);
}
for(String s : clientlist){
if(!masterlist.contains(s)) excess.add(s);
}