在Java中从文本文件复制到对象类型arrayList
我正在用基于控制台的java制作一个学生系统。我试图将文本文件的内容加载到ArrayList中,然后用学生注册号搜索,并列出他/她的姓名和课程。 我很难将文本文件内容加载到ArrayList中,以便以后可以将其作为对象检索
我制作了一个搜索功能,可以在Arraylist上完美运行(因为当输入一条新记录时,我会将它们放入Arraylist中,可以搜索到程序未关闭为止)
这是我尝试在ArrayList中加载文本文件时使用的方法:
try {
ArrayList<NewStudent> student = new ArrayList<>();
BufferedReader inFile = new BufferedReader (new FileReader ("Test.txt"));
String inputLine;
while ((inputLine = inFile.readLine())!=null) {
NewStudent ns = new NewStudent();
String[] studentVars = inputLine.split(":");
ns.setName(studentVars[0]);
student.add(ns);
}
System.out.print(student);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是我的搜索方法,非常有效
public Student Search(String ID, ArrayList<Student> StudentList) {
Student myStudent = new Student();
for(int i=0 ; i<StudentList.size() ; i++) {
if(StudentList.get(i).getID().equals(ID)) {
myStudent.setID(StudentList.get(i).getID());
myStudent.setName(StudentList.get(i).getName());
myStudent.setProgram(StudentList.get(i).getProgram());
return myStudent;
}
}
return null;
}
打印时,它会打印以下内容:
[com.Student.NewStudent@615e7597, com.Student.NewStudent@7a3e72, com.Student.NewStudent@5999ae9c, >>com.Student.NewStudent@7896b1b8, com.Student.NewStudent@6d6de4e1, com.Student.NewStudent@49cda7e7, com.Student.NewStudent@5cca548b]
如果我使用另一种方法,即:
BufferedReader inFile = new BufferedReader (new FileReader ("Student.txt"));
ArrayList<String> arrayList = new ArrayList<>();
String inputLine;
while ( (inputLine = inFile.readLine() ) != null) {
String[] stud = inputLine.split(":");
arrayList.add(stud[0]); \\if I add stud[1] it gives null pointer exception
}
System.out.println(arrayList);
这不会作为单独的对象返回。它显示了一条直线
这就是我的文本文件的样子
1112149 亚历克斯 理学士
1112155 塔玛拉 理学士
1112154 凯西 工商管理学士
1112114 约翰 巴布斯
每个对象都在不同的线上
# 1 楼答案
编辑:你想在:,但我在文本文件中没有看到:
改变
1112149亚历克斯理学学士
1112155塔马拉理学学士
1112154凯西工商管理学士
1112114约翰·巴布斯
到
1112149:Alexx:BSC
1112155:Tamara:BSC
1112154:Kathy:BBA
约翰:巴布斯
然后使用以下代码: