package com.senior.iostream;
import org.junit.Test;
import java.io.*;
/**
* @author eden
* @Description
* @create projectTest-com.senior.iostream:2021-05-13-21:58
* @since 对象流机制:把Java内存中的对象转换为与平台无关的二进制数据,并保存在硬盘中,或者通过网络将这种
* 二进制流传输到另一个网络节点。当其他程序获取了这种二进制流,再将其恢复成原来的java对象。
*/
public class ObjectStreamTest {
/*
* 序列化:把Java内存中的对象转换为与平台无关的二进制数据,并保存在硬盘中,或者通过网络将这种
* 二进制流传输到另一个网络节点。
* */
@Test
public void test() {
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream("object.dat"));
outputStream.writeObject(new String("PhD"));
outputStream.flush();//刷新操作
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//反序列化的过程
@Test
public void test1() {
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream("object.dat"));
Object o = inputStream.readObject();
if(o!=null)
{
System.out.println(o);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(inputStream!=null)
{
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
自定义可序列化类进行序列化然后再反序列化:
注意事项:
- 自定义类进行序列化和反序列化传输时,该类必须实现Serializable接口.
- 并且在类中必须提供一个用于标识该类的序列化Id,定义为全局常量
private static final long serialVersionUID = 1322347667710L;//数值要变化一下
- 该类中所有的成员属性都必须是可序列化的,默认基本数据类型就是可序列化的
//自定义可序列化类序列化
@Test
public void test2() {
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream("object.dat"));
outputStream.writeObject(new String("卡通人物统计"));
outputStream.flush();//刷新操作
outputStream.writeObject(new PersonCartoon("光头强","熊出没",30));
outputStream.flush();//刷新操作
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//反序列化自定义类的过程
@Test
public void test3() {
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream("object.dat"));
Object o = inputStream.readObject();
if (o != null) {
System.out.println(o);
}
Object o1 = inputStream.readObject();
if (o1 != null) {
System.out.println(o1);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class PersonCartoon implements Serializable {
//给可序列化的类提供一个唯一标识的序列号
private static final long serialVersionUID = 1322347667710L;
private String name;
private String source;
private int age;
public PersonCartoon() {
}
public PersonCartoon(String name, String source, int age) {
this.name = name;
this.source = source;
this.age = age;
}
@Override
public String toString() {
return "PersonCartoon{" +
"name='" + name + '\'' +
", source='" + source + '\'' +
", age=" + age +
'}';
}
}
该博客图片来源于尚硅谷宋老师教学课件