ObjectInputStream将写入的基本数据和对象进行反序列化。
import java.io.*;
class practice6
{
public static void main(String[] args) throws IOException,ClassNotFoundException
{
writeObj();
readObj();
//读取对象时,当读取的是以写好的对象,没有序列ID,当对类做修改时就会产生错误。错误下面图片说明。
System.out.println("Hello World!");
}
//写入对象---对象的序列化
public static void readObj()throws IOException,ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("keke.txt"));
Person obj = (Person)ois.readObject();
System.out.println(obj.getName()+" "+obj.getAge());
ois.close();
}
//读取对象---反序列化
public static void writeObj()throws IOException{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keke.txt"));
Person per = new Person("zhangsan",23);
oos.writeObject(per);
oos.close();
}
}
class Person implements Serializable//序列化接口
{
static final long serialVersionUID = 42L;
private int age;
private String name;
//private transient int age;//不参与序列化
Person(){}
Person(String name,int age){this.name = name;this.age = age;}
public int getAge(){
return age;
}
public String getName(){
return name;
}
}