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