使用字节输入流与字节输出流进行转换
对象需要实现Serializable接口
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
final Person person = new Person(18,"小王");
// 1、对象转字节数组
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(person);
byte[] bytes = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
objectOutputStream.close();
// 2、字节数组转对象
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
final ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
final Object object = objectInputStream.readObject();
final Person xiaowang = (Person) object;
byteArrayInputStream.close();
objectInputStream.close();
System.out.println(xiaowang);
}
@Data
@AllArgsConstructor
static class Person implements Serializable{
Integer age;
String name;
}
}