温馨提示×

java中怎么对比两个txt文本文档的数据

小亿
172
2023-11-03 12:42:02
栏目: 编程语言

在Java中,你可以使用以下步骤来对比两个txt文本文档的数据:

  1. 使用BufferedReader读取第一个txt文本的内容,并将其保存到一个ArrayListHashSet等数据结构中。
BufferedReader reader1 = new BufferedReader(new FileReader("file1.txt")); List<String> data1 = new ArrayList<>(); String line1; while ((line1 = reader1.readLine()) != null) { data1.add(line1); } reader1.close(); 
  1. 使用BufferedReader读取第二个txt文本的内容,并将其保存到另一个ArrayListHashSet中。
BufferedReader reader2 = new BufferedReader(new FileReader("file2.txt")); List<String> data2 = new ArrayList<>(); String line2; while ((line2 = reader2.readLine()) != null) { data2.add(line2); } reader2.close(); 
  1. 使用equals()方法逐行对比两个数据集。
boolean areEqual = data1.equals(data2); if (areEqual) { System.out.println("The content of the files is identical."); } else { System.out.println("The content of the files is not identical."); } 

注意:如果你需要按行对比而不是整个文本文件,请将每一行的内容保存到数据结构中,然后逐行对比。

0