Java序列化

今天在测试出现一个序列化的问题,一个类里有另一个类的引用,这两个类都必须要序列化,必须实现Serializable接口

说得简单一点,序列化就是讲内存中的对象数据进行持久化,一般是字节序列;反序列化就正好反过来,将字节序列读到内存当中;还有点,进程间发送Java对象数据,都是通过二进制字节序列来传送

序列化

首先创建OutputStream对象

然后将OutputStream对象封装到ObjectOutputStream对象里

调用writeObject()实现对象序列化

 

最后关闭资源objectOutputStream.close(), outputStream .close();

反序列化

首先创建InputStream对象

然后将InputStream对象封装到ObjectInputStream对象里

调用readObject()实现对象序列化

最后关闭资源objectInputStream.close(), inputStream .close();

Person类,里面包含了Man类引用

package com.lihuia.SerializableObject;

import java.io.Serializable;

/**
* Copyright (C), lihuia.com
* FileName: Person
* Author: lihui
* Date: 2018/12/1
*/

public class Person implements Serializable {

private static final long serialVersionUID = 1L;

private String name;
private String age;

private Man man;

public Person(String name, String age, Man man) {
this.name = name;
this.age = age;
this.man = man;
}

public String getName() {
return name;
}

public String getAge() {
return age;
}

public Man getMan() {
return man;
}
}

Man类,这里也必须要进行实现Serializable接口

package com.lihuia.SerializableObject;

import java.io.Serializable;

/**
* Copyright (C), lihuia.com
* FileName: Man
* Author: lihui
* Date: 2018/12/1
*/

public class Man implements Serializable {

private String sex;

public Man(String sex) {
this.sex = sex;
}

public String getSex() {
return sex;
}
}

测试类

package com.lihuia.SerializableObject;

import java.io.*;

/**
* Copyright (C), lihuia.com
* FileName: PersonTest
* Author: lihui
* Date: 2018/12/1
*/

public class PersonTest {

public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("lilei", "18", new Man("mail"));
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(new FileOutputStream(
new File("/Users/lihui/lilei.txt")
));
objectOutputStream.writeObject(person);
objectOutputStream.close();
System.out.println("序列化");

ObjectInputStream objectInputStream =
new ObjectInputStream(new FileInputStream(
new File("/Users/lihui/lilei.txt")
));
Person readPerson = (Person)objectInputStream.readObject();
System.out.println("反序列化");
System.out.println(readPerson.getName());
System.out.println(readPerson.getAge());
System.out.println(readPerson.getMan().getSex());
}
}

序列化后文本内容

��sr$com.lihuia.SerializableObject.PersonLagetLjava/lang/String;Lmant#Lcom/lihuia/SerializableObject/Man;Lnameq~xpt18sr!com.lihuia.SerializableObject.Man� �~?��Lsexq~xptmailtlilei%

OVER

发表回复