从文件中删除重复项
Removing duplicates from a file
我有一个文本文件。我想制作一组 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 来获取结果。
只需将每一行放入集合中,然后将集合的内容写入文件即可。 (是的,LinkedHashSet 实现保留顺序)
取决于日期是否始终保证相同:
- 如果是,则将所有行作为复合值添加到LinkedHashSet中,
- 如果否,则可能使用
Map
从值映射到日期。
因为你真正拥有的是两行的集合,而不是一行,所以这个问题比简单地逐行阅读并且只有 trim 行重复要复杂一些。
这是一个使用 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 资源。
我有一个文本文件。我想制作一组 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 来获取结果。
只需将每一行放入集合中,然后将集合的内容写入文件即可。 (是的,LinkedHashSet 实现保留顺序)
取决于日期是否始终保证相同:
- 如果是,则将所有行作为复合值添加到LinkedHashSet中,
- 如果否,则可能使用
Map
从值映射到日期。
因为你真正拥有的是两行的集合,而不是一行,所以这个问题比简单地逐行阅读并且只有 trim 行重复要复杂一些。
这是一个使用 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 资源。