我Externalization
在这个例子中使用。首先,我使用方法将对象序列化到名为“tmp”的文件中writeExternal()
。但是当我使用反序列化它时,readExternal()
我得到的输出如下......
default
The original car is name=Maruti
year2009
age10
The new Car is name=null
year0
age10
这里为什么没有连载车名和年份?如果被序列化,为什么我会得到null
它们0
的值......请指定..
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);
}
}**