public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
final Person person = new Person();
person.setAge(18);
person.setName("汤姆");
// 字节流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 对象输出流
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
// 将对象写入对象输出流
objectOutputStream.writeObject(person);
// 获取对象字节流
byte[] bytes = byteArrayOutputStream.toByteArray();
// 将字节数组写入
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
// 读取对象
Person person2 = (Person) objectInputStream.readObject();
System.out.println(person2);
}
@Data
static class Person implements Serializable {
private String name;
private Integer age;
}
}
在Java中使用字节流进行对象的序列化和反序列化
最新推荐文章于 2023-07-21 16:59:12 发布