【问题标题】:How to compare the content of two text files and output in another text file? text1 - text2如何比较两个文本文件的内容并在另一个文本文件中输出?文本 1 - 文本 2
【发布时间】:2014-09-18 14:49:16
【问题描述】:

我想将 1.txt 的内容减去 2.txt 并在 3.txt 中输出。另外如果 2.txt 有多余的剩余行,输出到 4.txt 中。

文本文件的内容不是逐行排序的,所以基本上代码只需要删除匹配的行,像这样:

1.txt 包含:

example1
example2
example3

2.txt 包含:

example2
example3
example4

3.txt 将包含:

example1

4.txt 将包含:

example4

【问题讨论】:

  • 您需要将此问题分解为多个步骤。想想如何逐行读写文件。一旦您可以逐行读取文件并将其写回,请考虑如何将其与另一个文件进行比较。从这些步骤中,您的家庭作业的答案将得到解决。
  • 使用一些Sets

标签: java collections hashmap comparison fileoutputstream


【解决方案1】:

使用Guava

Set<String> lines1 = 
    new HashSet<>(Files.readLines(new File("1.txt"), Charsets.UTF_8));
Set<String> lines2 = 
    new HashSet<>(Files.readLines(new File("2.txt"), Charsets.UTF_8));
Set<String> minus1 = Sets.difference(lines1, lines2);
Set<String> minus2 = Sets.difference(lines2, lines1);
Files.asCharSink(new File("3.txt"), Charsets.UTF_8).writeLines(minus1);
Files.asCharSink(new File("4.txt"), Charsets.UTF_8).writeLines(minus2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2022-10-13
    • 2020-01-31
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多