2016-01-24 51 views
0

寫了一段簡單的代碼將序列化的標準員工對象序列化並將其反序列化到來自不同類的同一臺機器中。這兩個程序都編譯並執行Obj輸出流來創建序列化對象。java.io.EOFException在通過ObjectInputStream讀取對象時

問題在於反序列化它。運行時編程會給出EOF異常。 這裏是我使用的代碼:

Serialize-

import java.io.*; 
public class OOStreamDemo{ 

public static void main(String []a){ 

Employee e = new Employee("Abhishek Yadav", 'i', 10014); 
FileOutputStream fout = null; 
ObjectOutputStream oout = null; 
try{ 
fout = new FileOutputStream("emp.ser"); 
oout = new ObjectOutputStream(fout); 

} catch(Exception ex1){ 
System.out.println(oout); 
    ex1.printStackTrace(); 

} 


finally{ 

try{ 
oout.flush(); 
oout.close(); 
fout.close(); 
} catch(IOException ex2){ 
    ex2.printStackTrace(); 

} 
} 
} 
} 

反序列化 -

import java.io.*; 
public class OIStreamDemo{ 
public static void main(String []a){ 

System.out.println("Inside main"); 

FileInputStream fin = null; 
ObjectInputStream oin = null; 
Employee emp; 

try{ 
System.out.println("Inside try"); 
fin = new FileInputStream("emp.ser"); 
oin = new ObjectInputStream(fin); 
System.out.println("Streams Initialized"); 
while((emp = (Employee)oin.readObject()) != null) 
    { 

System.out.println(emp.toString()); 
    } 
System.out.println("Object read"); 
//System.out.println("Read object is " + emp); 
//System.out.println("Obj props are "+ emp.name); 

} catch(Exception e){ 

    e.printStackTrace(); 
} 

} 

} 

這是的printStackTrace:

Inside main 
Inside try Streams 
Initialized 
java.io.EOFException 
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2598) 
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1318) 
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) 
at OIStreamDemo.main(OIStreamDemo.java:16) 

謝謝。

回答

3

你沒有寫Employee對象到ObjectOutputStrem因此添加

oout.writeObject(e); 
+0

謝謝了!當我寫代碼 – Abhi

+0

時,實現我應該更加小心一些請回答這個問題? http://stackoverflow.com/questions/37507890/java-io-eofexception-when-reading-weka-trained-model-file – CraZyDroiD

相關問題