// 使用stream方法实现 public static List<String> fileterData() throws IOException { String file1Content = new String(Files.readAllBytes(Paths.get(".\\src\\main\\resources\\File1"))); String file2Content = new String( Files.readAllBytes(Paths.get(".\\src\\main\\resources\\File2"))); // String 的 split方法有隐患,WINDOWS下换行符使用\r\n,Linux下使用的是\n List<String> file1Str = Arrays.asList(file1Content.split("\r\n")); List<String> file2Str= Arrays.asList(file2Content.split("\r\n")); // 过滤收集,遍历file1,每个都在file2中进行检查一遍,如果file2中没有的就收集起来 List<String> filtedStr = file1Str.stream().filter(t -> false == file2Str.contains(t)) .collect(Collectors.toList()); return filtedStr; }
上述是通过流的方式实现的,下面还有一种方法,通过BufferedReader,在读取文件的时候也略有差异:
// 找出file1中有但是file2中没有的数据 public static List<String> filterData() throws IOException { // TODO Auto-generated method stub String file1Path = ".\\src\\main\\resources\\File1"; String file2Path = ".\\src\\main\\resources\\File2"; BufferedReader file1br = new BufferedReader(new FileReader(file1Path)); BufferedReader file2br = new BufferedReader(new FileReader(file2Path)); String line = ""; List<String> file2String= new ArrayList<>(); while ((line = file2br.readLine()) != null) { file2String.add(line); } while ((line = file1br.readLine()) != null) { if (false == file2String.contains(line)) { System.out.println(line); } else { file2String.remove(line); } } return file2String; }
文件格式样例 File1:
String1
String2
String3
文件格式样例 File2:
String1
String2
String4
Thanks,
Ivan