java序列化

2021-03-13 19:35

阅读:441

public class TestJavaSerialization {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person zhansan = new Person();
zhansan.setAddress("hangzhou");
zhansan.setAge(30);
zhansan.setBirth(new Date());
zhansan.setName("zhansan");

//定义一个字节数组输出流
ByteArrayOutputStream os = new ByteArrayOutputStream();
//对象输出流
ObjectOutputStream out = new ObjectOutputStream(os);
//将对象写入到字节数组输出,进行序列化
out.writeObject(zhansan);
byte[] zhansanByte = os.toByteArray();

//字节数组输入流
ByteArrayInputStream is = new ByteArrayInputStream(zhansanByte);
//执行反序列化,从流中读取对象
ObjectInputStream in = new ObjectInputStream(is);
Person person = (Person)in.readObject();

System.out.println("name : " + person.getName() + ", age : " + person.getAge());
}
}

上一篇:C++&QT 的new用法

下一篇:Java__内部类


评论


亲,登录后才可以留言!