gpt4 book ai didi

java - 使用Java以随机顺序比较两个文本文件

转载 作者:搜寻专家 更新时间:2023-11-01 01:32:15 25 4
gpt4 key购买 nike

我正在尝试比较两个随机化的文本文件,并打印出两个文件中匹配的行。文件 1:

Student1
Student2
Student3
Student4

文件 2:

Student6
Student1
Student2

我想要输出为

Student1
Student2

我的代码如下。

public static void main(String[] args) throws IOException {

String first = "file1.txt";
String second = "file2.txt";
BufferedReader fBr = new BufferedReader(new FileReader(first));
BufferedReader sBr = new BufferedReader(new FileReader(second));




PrintWriter writer = new PrintWriter("test.txt", "UTF-8");
while ((first = fBr.readLine()) != null) {
String partOne1 = fBr.readLine();
String partTwo1 = sBr.readLine();
while ((second = sBr.readLine()) != null) {
System.out.println(first);
writer.println(first);
break;

}
}


writer.close();
fBr.close();
sBr.close();

最佳答案

这很简单=) 尝试存储第一个文件的所有结果并与第二个文件的所有行进行比较。它将是这样的:

package com.company;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Main {

public static void main(String[] args) throws IOException {

String first = "file1.txt";
String second = "file2.txt";
BufferedReader fBr = new BufferedReader(new FileReader(first));
BufferedReader sBr = new BufferedReader(new FileReader(second));

ArrayList<String> strings = new ArrayList<String>();

while ((first = fBr.readLine()) != null) {
strings.add(first);
}
fBr.close();

while ((second = sBr.readLine()) != null) {
if (strings.contains(second)) {
System.out.println(second);
}
}
sBr.close();
}
}

最好尽可能使用内存,不同 while 中的 'while' 会工作太长时间并混淆逻辑。

关于java - 使用Java以随机顺序比较两个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39208323/

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