2013-10-21 83 views
0

如何讀取文件中的對象我使用ObjectInputStream和ObjectOutputStream 類讀取和寫入我的自定義類的學生對象此類演示。java.io.StreamCorruptedException:在java代碼

代碼寫入和讀取使用::

  try 
      { 
       if(af.filepath==null || af.filepath=="")//file path 
       { 
        JOptionPane.showMessageDialog(null, "Please Set File Path", "File Path Error", JOptionPane.ERROR_MESSAGE); 
       } 
       else 
       { 
        FileOutputStream fs=new FileOutputStream(af.filepath,true); 
        ObjectOutputStream fo=new ObjectOutputStream(fs); 
        fo.writeObject(af.s);//write the Super Class Object 
        fo.close(); 
       } 

      } 
      catch (Exception ex) 
      { 
        System.out.println(ex); 
      } 

    --------------------------------------------------------------------------------- 
     try 
     { 
      if(af.filepath==null || af.filepath=="")//file path have whole path of the file 
      { 
       JOptionPane.showMessageDialog(null, "Please Set File Path", "File Path Error", JOptionPane.ERROR_MESSAGE); 
      } 
      else 
      { 
       Student sp; 
       FileInputStream fs=new FileInputStream(af.filepath); 
       ObjectInputStream fo=new ObjectInputStream(fs); 
       while ((sp=(Student)fo.readObject())!=null) 
       { 
        sp.set();//for print object 
       } 
       fo.close(); 
      } 

     } 
     catch (Exception ex) 
     { 
       ex.printStackTrace(); 
     } 

使用這個我看第一目標文件中,但之後提高

+0

哪裏錯誤上升粘貼錯誤 – Engineer

+1

java.io.StreamCorruptedException:無效的類型代碼:AC 在java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1356) 在java.io.ObjectInputStream.readObject(ObjectInputStream.java:351) 在MyPackage.MyCustomListener.actionPerformed(AddStudentFrame.java:171) 在javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19 95) –

+0

Visit this [link](http://stackoverflow.com/questions/2393179/streamcorruptedexception-invalid-type-code-ac)posibl e這將是有益的 – Engineer

回答

1

你已經寫了一個對象的錯誤,您正在嘗試讀取多個對象。當你試圖閱讀第二個,你肯定會得到一個異常。

如果你想讀回的對象數目不定...這樣...我建議你一個null到流:

fo.writeObject(null); 

(javadoc的不說你能做到這一點,但Java對象序列化規範說你可以,看到http://docs.oracle.com/javase/7/docs/platform/serialization/spec/output.html#933 ...步驟3)


另一個問題(這是什麼原因造成的損壞)是你正試圖序列化的對象附加到現有文件。這是行不通的。序列化協議指出,一個流包含一個頭,後跟零個或多個序列化對象......然後是文件的結尾。如果您將一個流附加到另一個流(例如FileOutputStream(path, true),額外的頭文件將使得組合文件在附加內容開始的位置可讀)

+0

我寫多個對象不僅是單個對象,當我讀取時,然後當讀指針到達第二個對象然後引發一個錯誤 –

相關問題