[英]reading data from a serialized file containing multiple objects
我正在尝试从包含一个类的多个对象的文件中读取数据。 但是我在将对象添加到列表时遇到空指针异常。 有人可以帮忙吗?
这是代码:
//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 次。
while(!flag){
Student st = oin.readObject();
if(st == null){
flag=true;
}
else{
studentList.add(st);
}
}
List <Student> studentList=null;
正在给出错误。 当您使用studentList.add((Student)oin.readObject());
到达要添加到studentList
的部分时studentList.add((Student)oin.readObject());
,该列表是一个空指针,因为您已将其初始化为空指针。
您可能希望将列表初始化为 null 以外的其他内容,例如List<Student> studentList = new ArrayList<Student>();
几个错误:
每次调用readObject()
,都会从流中读取下一个对象,因此以下几行:
if(oin.readObject()==null || oin.readObject().equals("")){ flag=true; } else{ studentList.add((Student)oin.readObject()); }
阅读 2 或 3 个对象,而不是只阅读一个。 他们应该是
Object read = oin.readObject()
if(read == null || read.equals("")){
flag=true;
}
else {
studentList.add((Student) read);
}
但是readObject()
永远不会返回 null,并且它不可能返回空字符串,因为您只在流中写入了 Student 的实例。
如果您只是将 4 个学生存储在List<Student>
并将此列表序列化,一切都会容易得多。 反序列化只是读取一个对象(因此,不需要循环):学生列表。
此外,关闭 ObjectOutputStream 将自动关闭 FileOutputStream。 ObjectInputStream 也是如此。 所以关闭文件流是不必要的。 为了更清洁、更安全的资源处理,您应该使用try-with-resources 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.