2016-01-26 101 views
0

本例中我使用的是Externalization。首先,我序列化的對象到一個名爲「TMP」使用writeExternal()方法。但是,當我使用我得到如下輸出反序列化它的文件...readExternal()不按預期工作?

default 
The original car is name=Maruti 
year2009 
age10 
The new Car is name=null 
year0 
age10 

這裏爲什麼叫和的一年汽車沒有序列化?如果是系列化,爲什麼我收到null0作爲自己的價值觀......請註明..

import java.io.*; 

class Car implements Externalizable 
{ 

    String name; 
    int year; 

    static int age; 
    public Car() 
    { 
     super(); 
     System.out.println("default"); 
    } 

    Car(String n,int y) 
    { 
     name=n; 
     year=y; 
     age=10; 
    } 

    public void writeExternal(ObjectOutput out) throws IOException 
    { 
     out.writeObject(name); 
     out.writeInt(year); 
     out.writeInt(age); 
    } 

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException 
    { 
     while(in.available()>0){ 
      name=(String)in.readObject(); 
      year=in.readInt(); 
      age=in.readInt(); 
     } 
    } 

    public String toString() 
    { 
     return("name="+name+"\n"+"year"+year+"\n" +"age" +age); 
    } 
} 

public class ExternExample 
{ 
    public static void main(String args[]) 
    { 
     Car car=new Car("Maruti",2009); 
     Car newCar=null; 
     try{ 
      FileOutputStream fout=new FileOutputStream("tmp"); 
      ObjectOutputStream so=new ObjectOutputStream(fout); 
      so.writeObject(car); 
      so.flush(); 
     } 
     catch(Exception e){System.out.println(e);} 
     try 
     { 
      FileInputStream fis=new FileInputStream("tmp"); 
      ObjectInputStream oin=new ObjectInputStream(fis); 
      newCar = (Car) oin.readObject(); 
     } 
     catch(Exception e){System.out.println(e);} 
     System.out.println("The original car is "+car); 
     System.out.println("The new Car is "+newCar); 
    } 
}** 

回答

3

擺脫環路和available()測試。你只寫了一個對象,所以你應該只讀一個對象,所以沒有理由循環,更不用說呼叫available()。該方法的正確用途很少,而且這不是其中之一。

如果您擴展Serializable而不是Externalizable,並簡單地刪除read/writeExternal()方法,它也可以工作。

您的主要方法是不關閉ObjectOutputStreamObjectInputStream.