对象的序列化

对象的序列化就是将对象转换为二进制的数据流,以便用于网络传输或者保存在文件上。
1.什么样的对象可以实现序列化操作
必须实现Serializable接口,在此接口具体的方法,此接口作为标识使用。表示本类的对象具备序列化的能力。
2.完成序列换需要借助的工具类。ObjectOutputStream ObjectInputStream
这两个类的构造方法要传入OutputStream 和InputStream作为参数。
3.在有些情况下,一个对象的某些属性不想被实例化,这个时候我们就可以在这个属性前面加上transient关键字,是的这个属性不被序列化。
4.如何是的一组对象被序列化。


First:
被序列化的对象

import java.io.Serializable;

public class Person implements Serializable {
private int age;
private String name;

public Person(String name,int age) {
super();
this.age = age;
this.name = name;
}

public String toString() {
return "姓名:" + this.name + "\t"+"年龄:" + this.age;
}
}



Second:被序列化过程

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamDemo {
public static void main(String[] args) throws Exception {
File file = new File("d:" + File.separator + "per.ser");
ObjectOutputStream oop = new ObjectOutputStream(new FileOutputStream(
file));
Person per = new Person("陈洁",31);
oop.writeObject(per);
oop.close();
}
}


Thrid:读出被序列化的对象

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class ObjectIntputStreamDemo {
public static void main(String[] args) throws Exception {
File file = new File("d:" + File.separator + "per.ser");
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
Person per=(Person)ois.readObject();
System.out.println(per);
}
}



Fourth:序列化一组对象

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class ArraySer {
public static void main(String[] args) throws Exception {
Person per[] = { new Person("张三", 30), new Person("李四", 31),
new Person("王五", 32) };
ser(per);
Person p[] = (Person[]) dser();
print(p) ;
}

public static void ser(Object obj) throws Exception {
File file = new File("d:" + File.separator + "person.ser");
ObjectOutputStream oos = null;
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(obj);
oos.close();
}

public static Object dser() throws Exception {
File file = new File("d:" + File.separator + "person.ser");
ObjectInputStream ois = null;
ois=new ObjectInputStream(new FileInputStream(file));
Object obj=ois.readObject();
return obj;
}

public static void print(Person per[]) {
for (Person p : per) {
System.out.println(p);
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值