开发者

How to read data from file(.dat) in append mode

开发者 https://www.devze.com 2022-12-31 09:15 出处:网络
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 and \"java.io.Stre

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 and "java.io.StreamCorruptedException:invalid type code:AC" when we are accessing other objects using a "for" loop.

        File file=null; 
         FileOutputStream fos=null; 
         BufferedOutputStream bos=null; 
         ObjectOutputStream 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(); 
} 


After you read an object from the input stream, the stream points to the next object.

Try (without reading from ois before):

MemberAccount m1 = null;
while( (m1=ois.readObject()) != null){ 
   System.out.println(m1.toString()); 
}


The grammar for serialized objects is defined as:

stream:
  magic version contents

By using the append option (new FileOutputStream(file,true);) you create a file with this data:

stream:
  magic version contents magic version contents magic version contents ....

This data does not conform to the specification and can't be decoded by ObjectInputStream.

0

精彩评论

暂无评论...
验证码 换一张
取 消