作用:
在很多应用中,需要对某些对象进行序列化,让它们离开内存空间,入住物理硬盘,以便长期保存。比如最常见的是Web服务器中的Session对象,当有 10万用户并发访问,就有可能出现10万个Session对象,内存可能吃不消,于是Web容器就会把一些seesion先序列化到硬盘中,等要用了,再把保存在硬盘中的对象还原到内存中。
当两个进程在进行远程通信时,彼此可以发送各种类型的数据。无论是何种类型的数据,都会以二进制序列的形式在网络上传送。发送方需要把这个Java对象转换为字节序列,才能在网络上传送;接收方则需要把字节序列再恢复为Java对象。
例子
下面创建一个people类
/**
* Copyright (C), 2018-2018,
* FileName: People
* Author: 大象
* Date: 2018-05-17 9:23
*/
package com.java.serializable;
import java.io.Serializable;
/**
* 〈〉<br>
*
* @author daxiang
* @create 2018-05-17
* @since 1.0.0
*/
public class People implements Serializable{
private static final long serialVersionUID = -4232667770371862548L;
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/**
* Copyright (C), 2018-2018,
* FileName: Test
* Author: 大象
* Date: 2018-05-17 9:22
*/
package com.java.serializable;
import java.io.*;
import java.text.MessageFormat;
/**
* 〈〉<br>
*
* @author daxiang
* @create 2018-05-17
* @since 1.0.0
*/
public class SerializableTest {
public static void main(String[] args) throws Exception {
SerializablePeople();//序列化Person对象
People p = DeserializePerson();//反序列Perons对象
System.out.println(MessageFormat.format("name={0},age={1},sex={2}",
p.getName(), p.getAge(), p.getSex()));
}
/**
* 序列化
*/
private static void SerializablePeople() throws Exception, IOException {
//构建对象
People people = new People();
people.setAge(12);
people.setName("张三");
people.setSex("男");
//序列化写入文件
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("people.txt")));
oo.writeObject(people);
oo.close();
}
/**
* 反序列化
*
* @return
* @throws Exception
* @throws IOException
*/
private static People DeserializePerson() throws Exception, IOException {
//读取文件
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
new File("people.txt")));
//提取对象
People people = (People) ois.readObject();
System.out.println("people对象反序列化成功!");
return people;
}
}