【发布时间】:2021-10-26 06:58:41
【问题描述】:
我可以逐行读取文本文件直到分隔符 -- 并将这些行写入新文件吗?
然后我想读取两个分隔符 -- 之间的下一行,并将它们与前面的行进行比较。
如果三行或更多行重复,则不要将它们写入文件。
以此类推直到结束。
public void removeDuplicateErr(String data) throws IOException {
String contents = new String(Files.readAllBytes(Paths.get(data)));
String[] blocks = contents.split("--");
String fileName = "output.txt";
PrintWriter pw = new PrintWriter(fileName);
int count = 0;
int count1 = 0;
for (String block : blocks) {
boolean flag = false;
if(count > 0) {
String contents1 = new String(Files.readAllBytes(Paths.get(fileName)));
String[] blocks1 = contents1.split("--");
for(String block1 : blocks1) {
BufferedReader br1 = new BufferedReader(new StringReader(block1));
String line1 = br1.readLine();
while (line1 != null) {
BufferedReader br2 = new BufferedReader(new StringReader(block));
String line2 = br2.readLine();
while (line2 != null) {
if(line1.equals(line2)) {
count1++;
if(count1 >= 3) {
flag = true;
break;
}
}
line2 = br2.readLine();
}
line1 = br1.readLine();
}
if (!flag) {
pw.print(block);
pw.print("--");
pw.flush();
}
}
}
if(count < 1) {
pw.print(block);
pw.print("--");
pw.flush();
}
count++;
}
pw.close();
}
输入样本
test 1
test 2
test 3
test 4
test 5
--
test 6
test 2
test 3
test 4
test 12
--
test 8
test 9
test 10
test 11
test 12
--
test 1
test 3
test 4
test 21
test 22
--
test 1
test 2
test 3
test 4
test 5
--
test 50
test 51
test 52
test 53
test 54
test 55
--
test 53
test 54
test 55
test 56
test 57
预期结果
test 1
test 2
test 3
test 4
test 5
--
test 8
test 9
test 10
test 11
test 12
--
test 50
test 51
test 52
test 53
test 54
test 55
【问题讨论】:
-
欢迎来到 SO!您尝试了什么(假设您有 Java File I/O 方面的经验)?请将您的代码尝试提供为minimal reproducible example 或至少显示您的研究成果(通过链接),例如搜索
[java] text file duplicate lines。 -
是否需要“--”分隔符?
-
获取带分隔符的文件
-
我问你想在结果的部分之间打印
--吗?因为这不会是一致的。你的第二部分可能只包含前面的重复,在这种情况下,你最终会得到“---”分隔符。 -
在结果中是没有必要的。
标签: java duplicates text-files