We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception when we are accessing other objects using a "for" loop.
File file=null;
FileOutputStream fos=null;
BufferedOutputStream bos=null;
ObjectOutputStre开发者_StackOverflow社区am oos=null;
try{
file=new File("account4.dat");
fos=new FileOutputStream(file,true);
bos=new BufferedOutputStream(fos);
oos=new ObjectOutputStream(bos);
oos.writeObject(m);
System.out.println("object serialized");
amlist=new MemberAccountList();
oos.close();
}
catch(Exception ex){
ex.printStackTrace();
}
Reading objects:
try{
MemberAccount m1;
file=new File("account4.dat");//add your code here
fis=new FileInputStream(file);
bis=new BufferedInputStream(fis);
ois=new ObjectInputStream(bis);
System.out.println(ois.readObject());
**while(ois.readObject()!=null){
m1=(MemberAccount)ois.readObject();
System.out.println(m1.toString());
}/*mList.addElement(m1);** // Here we have the issue throwing null pointer exception
Enumeration elist=mList.elements();
while(elist.hasMoreElements()){
obj=elist.nextElement();
System.out.println(obj.toString());
}*/
}
catch(ClassNotFoundException e){
}
catch(EOFException e){
System.out.println("end");
}
catch(Exception ex){
ex.printStackTrace();
}
The problem is your while loop:
while(ois.readObject()!=null){
m1=(MemberAccount)ois.readObject();
System.out.println(m1.toString());
}
You are reading an object from stream, check if it's not null and then read again from the stream. Now the stream can be empty returning null.
You could instead do this:
while( ois.available() > 0 ){
m1=(MemberAccount)ois.readObject();
System.out.println(m1.toString());
}
精彩评论