readExternal() not working as expected?

300 Views Asked by At

I am using Externalization in this example. First I serialized the object into the file named "tmp" using writeExternal() method .But when I am deserializing it using readExternal() i am getting the output as follows...

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

Here why the name and the year of the car is not serialized? And if is serialized, why i am getting null and 0 as their values...Please specify..

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);
    }
}**
1

There are 1 best solutions below

0
On

Get rid of the loop and the available() test. You've only written one object, so you should only read one object, so there is no reason to loop, let alone call available(). There are few correct uses of that method, and this isn't one of them.

If you extended Serializable instead of Externalizable and simply removed the read/writeExternal() methods it would work just as well.

Your main method isn't closing the ObjectOutputStream or ObjectInputStream.