【发布时间】:2017-01-05 14:34:15
【问题描述】:
我正在尝试比较两个随机的文本文件并打印出两个文件中匹配的行。 文件 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();
【问题讨论】:
-
您可以读取第一个文件中的所有行到
ArrayList<String>并在读取第二个文件时,如果第二个文件的每个字符串都存在于您的ArrayList 中,则通过方法tutorialspoint.com/java/util/arraylist_indexof.htm -
排序和合并...谷歌搜索
标签: java bufferedreader printwriter