Java序列化和反序列化

简介

序列化是将实例化对象转换成字节数组,反序列化是将字节数组转换成对象。

实例

前提

使需要序列化的类实现Serializable接口

1
public class MyMessage implements Serializable

序列化

1
2
3
4
5
6
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
byte[] buffer=byteArrayOutputStream.toByteArray();
objectOutputStream.close();
byteArrayOutputStream.close();

反序列化

1
2
3
4
5
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(buffer);
ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);
Object object=objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();

测试类源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Test {
public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException {
MyMessage message=new MyMessage("123","456","Hello",new Date());
File file=new File("F://temp");
FileOutputStream outputStream=new FileOutputStream(file);
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(message);
outputStream.write(byteArrayOutputStream.toByteArray());
objectOutputStream.close();
byteArrayOutputStream.close();
outputStream.close();
System.out.println("OK!");
File file2=new File("F://temp");
FileInputStream inputStream=new FileInputStream(file);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(buffer);
ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);
MyMessage message2=(MyMessage) objectInputStream.readObject();
System.out.println(message2.toString());
objectInputStream.close();
byteArrayInputStream.close();
inputStream.close();
}
}

测试结果为:

OK!
MyMessage [fromIp=123, toIp=456, text=Hello, image=null, date=Wed Sep 30 15:34:45 CST 2015]