我试图从包含一个类的多个对象的文件中读取数据。但在向列表中添加对象时,我得到了空指针异常。有人能帮忙吗?
代码如下:
//I'm following the same approach, but getting null Pointer exception while
//adding the object to a list. I'll post my code below. Can anyone help?
public class DeserializingMultipleObjects {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
//create few objects of student class and serialize them in a single file
Student st1= new Student(1, "abhishek", 24, 1);
Student st2= new Student(2, "Prashant",23,3);
Student st3= new Student(3,"Gayatri",22,2);
Student st4= new Student(4,"Ankul",23,4);
FileOutputStream fout= null;
FileInputStream fin= null;
ObjectInputStream oin=null;
ObjectOutputStream oout= null;
List <Student> studentList=null;
try{
fout= new FileOutputStream("Student.ser");
oout= new ObjectOutputStream(fout);
oout.writeObject(st1);
oout.writeObject(st2);
oout.writeObject(st3);
oout.writeObject(st4);
//objects have been serialized. Now read them and populate in a list
fin= new FileInputStream("Student.ser");
oin= new ObjectInputStream(fin);
boolean flag=false;
while(!flag){
if(oin.readObject()==null || oin.readObject().equals("")){
flag=true;
}
else{
studentList.add((Student)oin.readObject());
}
}
}
catch (ClassNotFoundException ex) {
Logger.getLogger(DeserializingMultipleObjects.class.getName()).log(Level.SEVERE, null, ex);
} finally{
if(fout !=null) try {
fout.close();
} catch (IOException ex) {
Logger.getLogger(DeserializingMultipleObjects.class.getName()).log(Level.SEVERE, null, ex);
}
if(oout !=null){
oout.close();
}
if(fin !=null){
fin.close();
}
if(oin !=null){
oin.close();
}
for(Student student: studentList){
System.out.println(student.name);
}
}
}
}
3条答案
按热度按时间yacmzcpb1#
List <Student> studentList=null;
正在给出错误。当到达要添加到的零件时studentList
具有studentList.add((Student)oin.readObject());
,列表是空指针,因为您已将其初始化为空指针。您可能希望将列表初始化为null以外的值,例如。
List<Student> studentList = new ArrayList<Student>();
enxuqcxy2#
每次迭代读取对象三次。
hzbexzde3#
有几个错误:
在开始读取文件之前,您忘记关闭objectoutputstream
每次你打电话
readObject()
,则从流中读取下一个对象,因此显示以下行:读两三个对象,而不是只读一个。他们应该是
但是
readObject()
将永远不会返回null,而且它也不可能返回空字符串,因为您在流中只编写了student的示例。如果你把你的4个学生储存在一个
List<Student>
并将此列表系列化。反序列化只需要读取一个对象(因此,不需要循环):学生列表。此外,关闭objectoutputstream将自动关闭fileoutputstream。objectinputstream也是如此。因此,关闭文件流是不必要的。为了更干净、更安全地处理资源,您应该使用try with resources。