2010-05-21 131 views
0

我们有一个应用程序要求我们使用反序列化动态读取文件(.dat)中的数据。当我们使用“for”循环访问其他对象时,我们实际上获取了第一个对象,并抛出了空指针异常和“java.io.StreamCorruptedException:无效类型代码:AC”。如何在追加模式下从文件(.dat)读取数据

 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(); 
     } 

阅读对象:

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(); 
} 
+0

这是一个确切的副本http://stackoverflow.com/questions/2879726/retrieve-data-from-dat-file – JoseK 2010-05-21 08:33:05

回答

0

在阅读从输入流对象,流点到下一个对象。

尝试(不前来自OIS读):您创建一个文件,这个

stream: 
    magic version contents 

通过使用附加选项(new FileOutputStream(file,true);):

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

grammar序列化对象定义为数据:

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

该数据不符合到规范并且不能被ObjectInputStream解码。