2012-07-06 57 views
0

我有一個類,其讀取學生[]數組對象java.io.EOFException的上FileOutputStream中

這裏的寫入的輸出是代碼

import java.io.*; 

// I use this class to read the final ouput "students_updated.dat" 
public class StudentArrayObjectFileReader { 

public static void main(String[] args) { 
    try { 
     ObjectInputStream fileReader = new ObjectInputStream(new FileInputStream("students_updated.dat")); 
     Student[] studs = (Student[]) fileReader.readObject(); 
     fileReader.close(); 

     // List the records in console 
     for (int i = 0; i < studs.length; i++) { 
      System.out.printf("%7d %-35s %-5s %1d %-6s%n",studs[i].getID(), studs[i].getName(), studs[i].getCourse(), studs[i].getYr(), studs[i].getGender()); 
     } 
    } catch (FileNotFoundException fnfe) { 

     fnfe.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

問題是,它讀出時有錯誤在Student[] studs = (Student[]) fileReader.readObject();

這裏說

java.io.EOFException 
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571) 
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315) 
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369) 
at StudentArrayObjectFileReader.main(StudentArrayObjectFileReader.java:9) 

上的任何想法是什麼可能是問題?在此先感謝..

這是怎麼students_updated.dat

public void saveStudentArray() { // studs print to student_updated.dat 
    try{ 
     output.writeObject(studs); // write the final studs 
     output.close(); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 

在哪裏這個方法是

回答

1

檢查students_updated.dat文件的內容。 readObject()函數期望文件包含一個序列化的對象。

該文件是否包含序列化對象?檢查序列化是否成功,沒有任何問題?

如果您嘗試從純文本文件構建數組,則不應使用readObject()。

訪問此鏈接如何序列化和反序列化數組中的樣本 - Can I serialize an array directly...

+0

的方式寫對象之前它是事實該對象數組未被序列化。謝謝! – 2012-07-06 17:10:54

1

移動這條線的構造宣佈ObjectInputStream

fileReader.close(); 

在您的for循環之後。

在Java中,創建變量只是創建對內存中某個位置的引用。將從fileReader中讀取的對象投射到您的學生數組中只會創建一個指向內存中正確位置的指針。如果您然後通過關閉fileReader刪除該地點,您將刪除指向的位置studs

+0

它仍然返回相同的異常。我也沒有使用'fileReader.close()'嘗試它,但沒有它的工作機會。 – 2012-07-06 16:44:35

+0

你確定你的文件裏有東西嗎?這些數據如何被編碼? – 2012-07-06 16:49:55

+0

是的,裏面有一個學生[],我用一個'system.out.print();'在控制檯中出現,它的內容 – 2012-07-06 17:02:07