Thanks
Java中的序列化
对象是存储在内存中,但如果我们想把对象持久化存到硬盘上该怎么做呢?在Java中,可以使用序列化:Serialization(序列化)是一种将对象以一连串的字节描述的过程;反序列化deserialization是一种将这些字节重建成一个对象的过程。
简单例子
Java中必须实现接口Serializable才能够被序列化,而Serializable接口没有方法,更像是个标记。 有了这个标记的Class就能被序列化机制处理。
简单定义一个需要序列化的类:
public class Person implements Serializable{
public int height = 180;
private int age = 21;
}
然后进行序列化
public class Main {
public static void main(String args[]) throws IOException {
FileOutputStream fos = new FileOutputStream("temp.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Person ts = new Person();
oos.writeObject(ts);
oos.flush();
oos.close();
}
}
序列化后保存到一份文件里面,文件内容如下,这些内容是有特定含义,
aced 0005 7372 0022 736f 7572 6365 436f
6465 2e74 6573 7453 6572 6961 6c69 7a61
626c 652e 5065 7273 6f6e e400 6d6d fbe4
589a 0200 0249 0003 6167 6549 0006 6865
6967 6874 7870 0000 0015 0000 00b4
一堆的16进制,保存的就是对象的属性了,如果我们再反序列话出来,就得到原来的对象。
public static void main(String args[]) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("temp.out");
ObjectInputStream oin = new ObjectInputStream(fis);
Person person = (Person) oin.readObject();
S