62,628
社区成员
发帖
与我相关
我的任务
分享package day21;
import java.io.*;
public class ObjectStreamDemo {
public static void main(String[] args)throws Exception
{
writeObj();
readObj();
}
public static void readObj()throws Exception
{
//写入的是对象,读取的时候就要用对应的对象读取流
ObjectInputStream oip = new ObjectInputStream(new FileInputStream("C:\\Users\\Administrator\\Desktop\\a.txt"));
//oip.readObject();//这里会抛出ClassNotFoundException异常,返回值类型是Object
System.out.println((Person)oip.readObject());
System.out.println((Person)oip.readObject());
oip.close();
}
public static void writeObj()throws IOException
{
ObjectOutputStream oop = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\a.txt"));
oop.writeObject(new Person("李元霸",18,"mb"));
oop.writeObject(new Person("李建成",26,"kc"));
oop.flush();
oop.close();
System.out.println("over");
}
}
//这里的自定义类如果想要被序列化需要实现一个接口
class Person implements Serializable
{
//类实现了Serializable之后会的到一个序列号,这个序列号根据类中的内容算出来的,所以类中的内容一旦发生改变,序列号就变了
//所以这时我们需要自己定义一个序列号来取代java自动分配的序列号
public static final long serialVersionUID = 42L;
//给出自定义的序列号之后,就算改变类中的内容,Object流也能识别了
private String name;
//对与非静态的怎样让其不能序列化?
//加上关键字transient
transient int age;
//注意:静态不能被序列化,序列化是将堆内的数据序列话,而静态在方法区里面....1.8貌似可以了
static String country="cn";
Person(String name,int age,String country)
{
this.name=name;
this.age=age;
this.country=country;
}
public String toString()
{
return name+":::"+age+"==="+country;
}
}