序列化流ObjectOutputStream、ObjectInputStream以及实现Java深克隆
package com.zzhua.entity;
import java.io.Serializable;
public class Person implements Serializable {
// 不指定版本的话, jdk会默认根据当前的类信息生成一个版本号,
// 等下次你改了什么地方又会是另一个版本号,或者不同jdk版本版本号又会不同,
// 在反序列化的时候,一旦版本号没匹配上,就会报错了,所以最好是指定固定的一个版本号
// (要反序列化的话,必须提供Class,因此就会检测版本号)
private static final long serialVersionUID = 1984769201788957020L;
private String name;
private Long p = 3L;
private int age;
private int b = 6;
public Person(String name, int age) {
System.out.println("唯一构造方法");
this.name = name;
this.age = age;
}
}
测试
package com.zzhua.test;
import com.zzhua.entity.Person;
import org.junit.Test;
import java.io.*;
import java.util.Base64;
public class Test01 {
@Test
public void test01() throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:\\Projects\\practice\\demo-serialize\\src\\main\\resources\\a.tmp"));
// Person p = new Person("zj", 22);
//
// objectOutputStream.writeObject(p);
// objectOutputStream.flush();
}
@Test
public void test02() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\Projects\\practice\\demo-serialize\\src\\main\\resources\\a.tmp"));
Object o = objectInputStream.readObject();
System.out.println(o);
}
@Test
public void test03() throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(baos);
Person p = new Person("zj", 22);
objectOutputStream.writeObject(p);
objectOutputStream.flush();
objectOutputStream.close();
byte[] bytes = baos.toByteArray();
String s = new String(Base64.getEncoder().encode(bytes));
System.out.println(s);
byte[] decode = Base64.getDecoder().decode(s.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(decode);
ObjectInputStream objectInputStream = new ObjectInputStream(bais);
Object o = objectInputStream.readObject();
System.out.println(o);
// 既然可以存入到字节数组,转成字符串, 当然也可以存入到redis,然后获取字节数据,再反序列化回对象
}
}