获取两个txt文档的内容~存储进集合中求集合的并集/交集/补集/差集
package com.sxd.readLines.aboutDB;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;
public class Test {
/**
*
* @throws IOException
*/
@org.junit.Test
public void test1() throws IOException {
Set<String> set1 = readFile4List(new File("D:/B/1.txt"));
Set<String> set2 = readFile4List(new File("D:/B/DB.txt"));
Set<String> result1 = Sets.union(set1, set2);//合集,并集
Set<String> result2 = Sets.intersection(set1, set2);//交集
Set<String> result3 = Sets.difference(set1, set2);//差集 1中有而2中没有的
Set<String> result4 = Sets.symmetricDifference(set1, set2);//相对差集 1中有2中没有 2中有1中没有的 取出来做结果
//可以分别把4种不同结果 写出文件
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File("d:/B/result.txt")));
bufferedWriter.write("共有:"+result1.size()+"条\r\n");
for (String string : result1) {
bufferedWriter.write(string+"\r\n");
}
bufferedWriter.close();
}
public Set<String> readFile4List(File file) throws IOException{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
Set<String> set = new HashSet<String>();
String str = null;
while((str =bufferedReader.readLine()) != null){
if(str.length() > 6){
set.add(str.substring(3));
}else{
set.add(str);
}
}
return set;
}
}