gpt4 book ai didi

java - 从文件中删除重复项

转载 作者:太空宇宙 更新时间:2023-11-04 14:07:29 24 4
gpt4 key购买 nike

我有一个文本文件。我想制作一组 4 行并检查这 4 行是否唯一。如果它们是唯一的,请将其复制到另一个文本文件。

file.txt 包含:

abc
12:12:11
john
12/25/2014
abc
12:12:11
doe
12/25/2014
abc
12:12:11
john
12/25/2014

新的 txt 文件应该只显示。

abc
12:12:11
john
12/25/2014
abc
12:12:11
doe
12/25/2014

and delete
abc
12:12:11
john
12/25/2014

有什么方法可以在Java中做到这一点吗?我不知道如何使用 LinkedHashSet 来获取结果。

最佳答案

由于您真正拥有的是两行集,而不是一行,因此问题比简单地逐行读取并仅删除重复项要复杂一些。

这是使用 Java 7 的解决方案:

public static void eliminateDups(final String srcfile, final String dstfile)
throws IOException
{
final StringBuilder sb = new StringBuilder();
final Set<String> seen = new HashSet<>();
final Charset charset = StandardCharsets.UTF_8;

final Path src = Paths.get(srcfile);
final Path dst = Paths.get(dstfile);

try (
final BufferedReader reader = Files.newBufferedReader(src, charset);
final BufferedWriter writer = Files.newBufferedWriter(dst, charset,
StandardOpenOption.TRUNCATE_EXISTING);
) {
String line1, line2;
while ((line1 = reader.readLine()) != null) {
line2 = reader.readLine();
sb.setLength(0);
if (!seen.add(sb.append(line1).append(line2).toString()))
continue;
writer.write(line1);
writer.newLine();
writer.write(line2);
writer.newLine();
}
}
}
<小时/>

对于 Java 6,我建议您使用 Guava 及其 Closer 来管理您的 I/O 资源。

关于java - 从文件中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28701163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com