java---Serializable(序列化)

来源:互联网 发布:离心泵设计软件 编辑:程序博客网 时间:2024/06/05 07:19
1、什么是序列化和反序列化

Serialization(序列化)是一种将对象以一连串的字节描述的过程;反序列化deserialization是一种将这些字节重建成一个对象的过程。

2、什么情况下需要序列化 
a)当你想把的内存中的对象保存到一个文件中或者数据库中时候;
b)当你想用套接字在网络上传送对象的时候;

3、如何实现序列化

将需要序列化的类实现Serializable接口,Serializable接口中没有任何方法,可以理解为一个标记,即表明这个类可以序列化。

package ThreadIO2_1.IO.seriailizable;import java.io.Serializable;public class Address implements Serializable {/** * 静态变量是不会被序列化的。对于非静态变量, * 一般情况下都会被序列化,  * 但如果声明成transient型则不会 transient(瞬时变量) */transient int num;//瞬时变量---该变量是不会被序列化的---不会出现在对象图中的private String name;private int age;private String tel;public Address(String name, int age, String tel) {super();this.name = name;this.age = age;this.tel = tel;}public Address(int num, String name, int age, String tel) {super();this.num = num;this.name = name;this.age = age;this.tel = tel;}@Overridepublic String toString() {return "Address [num=" + num + ", 姓名=" + name + ", 年龄=" + age+ ",电话=" + tel + "]";}}




package io.serializable;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStream;public class SerializableDemo {public static void main(String[] args) throws Exception {       //demo1();demo2();}private static void demo2() throws FileNotFoundException, IOException,ClassNotFoundException {//对象序列化---输出,写OutputStream fout = new FileOutputStream("a.txt");ObjectOutputStream out = new ObjectOutputStream(fout);out.writeObject( new Address(1,"aa",23,"13588888888"));out.writeObject( new Address(2,"bb",24,"13566666666"));out.writeObject( new Address(3,"cc",23,"13577777777"));out.writeObject( new Address(4,"dd",25,"13599999999"));out.close();//反序列化----读InputStream fin = new FileInputStream("a.txt");ObjectInputStream in = new ObjectInputStream(fin);System.out.println( in.readObject() );System.out.println( in.readObject() );System.out.println( in.readObject() );System.out.println( in.readObject() );}
       private static void demo1() throws FileNotFoundException, IOException,        ClassNotFoundException {//对象序列化---输出,写OutputStream fout = new FileOutputStream("a.txt");ObjectOutputStream out = new ObjectOutputStream(fout);out.writeObject( new Address("aa",23,"13588888888"));out.writeObject( new Address("bb",24,"13566666666"));out.writeObject( new Address("cc",23,"13577777777"));out.writeObject( new Address("dd",25,"13599999999"));out.close();//反序列化----读InputStream fin = new FileInputStream("a.txt");ObjectInputStream in = new ObjectInputStream(fin);System.out.println( in.readObject() );System.out.println( in.readObject() );System.out.println( in.readObject() );System.out.println( in.readObject() );}}



0 0
原创粉丝点击