import java.io.*;
class Person implements Serializable
{
public static final long serialVersionUID = 42L;//自定义UID
//静态不能被序列化。
private String name;
private transient int age;//不是静态,transient修饰也不会被序列化
Person(String name,int age){
this.name = name;
this.age = age;
}
public void toString(){
return name+":"+age;
}
}
import java.io.*;
class ObjectOutputStreamDemo
{
public static void main(String[] args)throws Exception{
writeObj();
readObj();
}
public static void readObj()throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
public static void writeObj()throws IOException{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));//对象存储位置
oos.writeObject(new Person("lisi",39));//存到文件
oos.close();
}
}
IO流--对象的序列化
最新推荐文章于 2024-10-12 23:49:35 发布