获取两个txt文档的内容~存储进集合中求集合的并集/交集/补集/差集
1 package com.sxd.readLines.aboutDB; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.File; 6 import java.io.FileReader; 7 import java.io.FileWriter; 8 import java.io.IOException; 9 import java.util.HashSet; 10 import java.util.Set; 11 12 import com.google.common.collect.Sets; 13 14 public class Test { 15 16 /** 17 * 18 * @throws IOException 19 */ 20 21 @org.junit.Test 22 public void test1() throws IOException { 23 Set<String> set1 = readFile4List(new File("D:/B/1.txt")); 24 Set<String> set2 = readFile4List(new File("D:/B/DB.txt")); 25 26 Set<String> result1 = Sets.union(set1, set2);//合集,并集 27 Set<String> result2 = Sets.intersection(set1, set2);//交集 28 Set<String> result3 = Sets.difference(set1, set2);//差集 1中有而2中没有的 29 Set<String> result4 = Sets.symmetricDifference(set1, set2);//相对差集 1中有2中没有 2中有1中没有的 取出来做结果 30 31 //可以分别把4种不同结果 写出文件 32 33 BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File("d:/B/result.txt"))); 34 bufferedWriter.write("共有:"+result1.size()+"条 "); 35 for (String string : result1) { 36 bufferedWriter.write(string+" "); 37 } 38 bufferedWriter.close(); 39 40 41 } 42 43 public Set<String> readFile4List(File file) throws IOException{ 44 BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); 45 Set<String> set = new HashSet<String>(); 46 String str = null; 47 while((str =bufferedReader.readLine()) != null){ 48 if(str.length() > 6){ 49 set.add(str.substring(3)); 50 }else{ 51 set.add(str); 52 } 53 54 } 55 return set; 56 } 57 58 59 }