文字描述来自:http://blog.youkuaiyun.com/dreamtdp/article/details/15378329
1、序列化是干什么的?
简单说就是为了保存在内存中的各种对象的状态(也就是实例变量,不是方法),并且可以把保存的对象状态再读出来。虽然你可以用你自己的各种各样的方法来保存object states,但是Java给你提供一种应该比你自己好的保存对象状态的机制,那就是序列化。2、什么情况下需要序列化
a)当你想把的内存中的对象状态保存到一个文件中或者数据库中时候;
b)当你想用套接字在网络上传送对象的时候;
c)当你想通过RMI传输对象的时候;
3、当对一个对象实现序列化时,究竟发生了什么?
在没有序列化前,每个保存在堆(Heap)中的对象都有相应的状态(state),即实例变量(instance ariable)比如:
MyFoo对象中的width和Height实例变量的值(37,70)都被保存到foo.ser文件中,这样以后又可以把它
从文件中读出来,重新在堆中创建原来的对象。当然保存时候不仅仅是保存对象的实例变量的值,JVM还要保存一些小量信息,比如类的类型等以便恢复原来的对 象。
写入静态对象反序列化取出以后两个是一致的。
public class test implements Serializable{
int a;
int b;
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public static void main(String arsg[]) throws IOException {
test t=new test();
t.setA(5);
FileOutputStream fileout = null;
ObjectOutputStream object;
Date d = null;
try {
fileout = new FileOutputStream("C:\\Users\\绝影\\Desktop\\conf.txt");
object=new ObjectOutputStream(fileout);//对象输出流
d=new Date();
object.writeObject(t);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
fileout.close();
}
FileInputStream filein=new FileInputStream(new File("C:\\Users\\绝影\\Desktop\\conf.txt"));//文件输出流
ObjectInputStream input=new ObjectInputStream(filein);//对象输入流
test r = null;
try {
r = (test) input.readObject();
r.setB(6);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
filein.close();
}
System.out.println(r);
System.out.println(r.getA()+"ggg"+r.getB());
System.out.println(t);
System.out.println(t.getA()+"ggg"+t.getB());
}
}