【问题标题】:readExternal() not working as expected?readExternal() 没有按预期工作?
【发布时间】:2016-05-03 17:39:31
【问题描述】:

我在这个例子中使用Externalization。首先,我使用writeExternal() 方法将对象序列化为名为“tmp”的文件。但是当我使用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);
    }
}**

【问题讨论】:

    标签: java serialization externalizable


    【解决方案1】:

    摆脱循环和available() 测试。你只写了一个对象,所以你应该只读取一个对象,所以没有理由循环,更不用说调用available()。该方法的正确用法很少,这不是其中之一。

    如果您扩展 Serializable 而不是 Externalizable 并简单地删除 read/writeExternal() 方法,它也可以正常工作。

    您的主要方法不是关闭ObjectOutputStreamObjectInputStream.

    【讨论】: