序列化

来源:互联网 发布:登陆传奇永恒网络异常 编辑:程序博客网 时间:2024/05/14 21:40
概念:
就是将对象输入输出。


语法:
String path = "D:" + File.separator + "soft" + File.separator + "object.txt";
OutputStream ops = new FileOutputStream(path);
InputStream ips = new FileInputStream(path);
ObjectOutputStream oops = new ObjectOutputStream(ops);
oops.writeObject(new Person("haoren",12));
oops.close();


ObjectInputStream oips = new ObjectInputStream(ips);
Object o =oips.readObject();
System.out.print(o);


注:
1:被序列化的类都必须实现Serializable接口


2:transient关键字:用它声明表示这个属性就不会被序列化。


3:序列化主要是对属性的序列化。


多个对象的存和度:
Person[] p = {new Person("haoren",34),new Person("huairen",33)};
String path = "D:" + File.separator + "soft" + File.separator + "object.txt";
OutputStream ops = new FileOutputStream(path);
InputStream ips = new FileInputStream(path);
ObjectOutputStream oops = new ObjectOutputStream(ops);
oops.writeObject(p);
oops.close();

ObjectInputStream oips = new ObjectInputStream(ips);
Object[] b = (Object[]) oips.readObject();
for(int i=0;i<b.length;i++){
System.out.println(b[i]);
}
oips.close();


注:运用数组接受对象。
0 0
原创粉丝点击