2013-03-02 108 views
2

我正在寫一個類來跟蹤比賽中的比賽數據。我想把這個類存儲到一個文件中,所以我使用了ObjectInputStream。我正在編寫的類實現了Serializable。我得到了EOFException,我在SO和其他地方找到的解決方案都沒有解決這個問題。ObjectInputStream拋出EOFException

我的文件作家是:

public void writeToFile(String path) { 
    File f = new File(path); 
    if(f.exists()) f.delete(); 

    try { 
     OutputStream fileOut = new FileOutputStream(path); 
     OutputStream bufferOut = new BufferedOutputStream(fileOut); 
     ObjectOutput output = new ObjectOutputStream(bufferOut); 

     output.writeObject(this); 
    } catch(IOException e) {} 
} 

我的文件閱讀器:

public static DivisionDataFTC readFromFile(String path) { 
    try { 
     InputStream fileIn = new FileInputStream(path); 
     InputStream bufferIn = new BufferedInputStream(fileIn); 
     ObjectInput input = new ObjectInputStream(bufferIn); 

     System.out.println(input.read()); 
    } catch(Exception e) { 
     System.out.println(path); 
     e.printStackTrace(); 
    } 

    if(1==1) throw new Error("Could not read DivisionDataFTC at " + path); 
    return null; 
} 

我成功寫入數據 - 我已經驗證該文件是空。 (其內容如果相關,一致7.99kb)。

要清楚的是,在ObjectOutputStream的實例化中不會發生錯誤。這就是這個問題的不同之處 - 錯誤發生在readObject()調用上。我的輸出是一個相當長的EOFException

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 java.util.ArrayList.readObject(ArrayList.java:733) 
    (...cut out most of this because nobody wants to read it...) 
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369) 
    at tournamentftc.DivisionDataFTC.readFromFile(DivisionDataFTC.java:297) 
    at firstscouting.FIRSTScouting.runGUI(FIRSTScouting.java:82) 
    at firstscouting.FIRSTScouting.main(FIRSTScouting.java:101) 
Exception in thread "main" java.lang.Error: Could not read DivisionDataFTC at C:\Users\Noah\Desktop\out.ser 
    at tournamentftc.DivisionDataFTC.readFromFile(DivisionDataFTC.java:303) 
    at firstscouting.FIRSTScouting.runGUI(FIRSTScouting.java:82) 
    at firstscouting.FIRSTScouting.main(FIRSTScouting.java:101) 

我不知道爲什麼會這樣。我該如何處理?

回答

5

你應該關閉的ObjectOutputStream,儘量

ObjectOutput output = new ObjectOutputStream(bufferOut); 
output.writeObject(this); 
output.close(); 
3

您需要關閉輸出流,你也孃家打電話的readObject()不讀。

相關問題