我正在尝试编写一个程序来检查两个文件并打印这两个文件中的共同内容。
文件 1 内容的示例为:
James 1
Cody 2
John 3
文件 2 内容的示例为:
1 Computer Science
2 Chemistry
3 Physics
所以控制台上打印的最终输出将是:
James Computer Science
Cody Chemistry
John Physics
这是我到目前为止在代码中的内容:
public class Filereader {
public static void main(String[] args) throws Exception {
File file = new File("file.txt");
File file2 = new File("file2.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String st, st2;
while ((st = reader.readLine()) != null) {
System.out.println(st);
}
while ((st2 = reader2.readLine()) != null) {
System.out.println(st2);
}
reader.close();
reader2.close();
}
}
我无法弄清楚如何匹配文件内容,并通过匹配每个文件中的学生 ID 来仅打印学生姓名及其专业。感谢您的所有帮助。
最佳答案
您可以使用其他答案并为每个文件创建一个对象,例如数据库中的表。
public class Person{
Long id;
String name;
//getters and setters
}
public class Course{
Long id;
String name;
//getters and setters
}
您可以对列进行更多控制,而且使用起来很简单。
此外,您将使用ArrayList<Person>
和一个 ArrayList<Course>
您的关系可以是对象内的变量,例如 courseId
在Person
类或其他东西。
if(person.getcourseId() == course.getId()){
...
}
如果匹配的是文件的第一个数字,则使用 person.getId() == course.getId()
。
PS:请勿不要使用split(" ")
在您的情况下,因为您可以拥有具有两个值的其他对象,即 1 Computer Science
.
关于java - 用Java打印2个文件的匹配信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50220868/