Java中的Serializable

来源:互联网 发布:南昌数据分析培训班 编辑:程序博客网 时间:2024/04/29 04:18

1、序列化是干什么的?

  简单说就是为了保存在内存中的各种对象的状态(也就是实例变量,不是方法),并且可以把保存的对象状态再读出来。虽然你可以用你自己的各种各样的方法来保存object states,但是Java给你提供一种应该比你自己好的保存对象状态的机制,那就是序列化。

2、什么情况下需要序列化  

    a)当你想把的内存中的对象状态保存到一个文件中或者数据库中时候;

    b)当你想用套接字在网络上传送对象的时候;

    c)当你想通过RMI传输对象的时候;

3、当对一个对象实现序列化时,究竟发生了什么?

    在没有序列化前,每个保存在堆(Heap)中的对象都有相应的状态(state),即实例变量(instance ariable)比如:  

java 代码

1.Foo  myFoo = new Foo(); 

2.myFoo .setWidth(37); 

3.myFoo.setHeight(70); 

    通过下面的代码序列化之后,MyFoo对象中的widthHeight实例变量的值(3770)都被保存到foo.ser文件中,这样以后又可以把它 从文件中读出来,重新在堆中创建原来的对象。当然保存时候不仅仅是保存对象的实例变量的值,JVM还要保存一些小量信息,比如类的类型等以便恢复原来的对 象。

java 代码

1.FileOutputStream fs = new FileOutputStream("foo.ser"); 

2.ObjectOutputStream os = new ObjectOutputStream(fs); 

3.os.writeObject(myFoo); 

4、实现序列化(保存到一个文件)的步骤

       1Make a FileOutputStream  //创建个Fileoutputsteam         

FileOutputStream fs = new FileOutputStream("foo.ser");   

       2Make a ObjectOutputStream    //创建个objiectoutputstream       

ObjectOutputStream os =  new ObjectOutputStream(fs);  

       3write the object  //写入特定类的对象, 用方法writeobjiect()

os.writeObject(myObject1); 

os.writeObject(myObject2); 

os.writeObject(myObject3); 

      4) close the ObjectOutputStream //关闭流。

os.close(); 

5、举例说明

java 代码

1.import java.io.*;

3.public class  Box  implements  Serializable  //要保存的对象类必须实现序列化接口serializable

4.{ 

5.    private int width; 

6.    private int height; 

7. 

8.    public void setWidth(int width){ 

9.        this.width  = width; 

10.    } 

11.    public void setHeight(int height){ 

12.        this.height = height; 

13.    } 

14.

15.    public static void main(String[] args){ 

16.        Box myBox = new Box(); 

17.        myBox.setWidth(50); 

18.        myBox.setHeight(30); 

19. 

20.        try{  //序列化。

21.            FileOutputStream fs = new FileOutputStream("foo.ser"); 

22.            ObjectOutputStream os =  new ObjectOutputStream(fs); 

23.            os.writeObject(myBox); 

24.            os.close(); 

25.        }catch(Exception ex){ 

26.            ex.printStackTrace(); 

27.        } 

28.    }     

30.} 

 

 发序列化方法

Public static void seserialize(string filename) throws Exception

{

           // 反序列化(读出保存的对象文件)

ObjectInputStream in = new ObjectInputStream (new FileInputStream(filename));

Box box = (Box) (in.readbject());

System.out.println(box.toString());

In.Closer();

}