Java 提供了一种对象序列化的机制,该机制中,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据、有关对象的类型的信息和存储在对象中数据的类型。
将序列化对象写入文件之后,可以从文件中读取出来,并且对它进行反序列化,也就是说,对象的类型信息、对象的数据,还有对象中的数据类型可以用来在内存中新建对象。
整个过程都是Java虚拟机(JVM)独立的,也就是说,在一个平台上序列化的对象可以在另一个完全不同的平台上反序列化该对象。
package com.demo.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
public class SerializableDemo {
static class Person implements Serializable {
private static final long serialVersionUID = 1L;
//常量和transient修饰的变量一样不会被序列化
private static final String TEST_CONST = "test const";
private String name;
private int age;
private boolean isMale;
private Date birthday;
private byte[] data;
// transient短暂的,不会被序列化或者反序列化
private transient String password;
public Person(String name, int age, boolean isMale, Date birthday, byte[] data, String password) {
this.name = name;
this.age = age;
this.isMale = isMale;
this.birthday = birthday;
this.data = data;
this.password = password;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", isMale=" + isMale + ", birthday=" + birthday + ", data=" + Arrays.toString(data) + ", password=" + password + "]";
}
}
public static void main(String[] argv) {
Person p = new Person("bob", 24, true, new Date(), new byte[] { 1, 2, 3, 4, 5, 6 }, "123456");
System.out.println("secerialize = " + p);
String path = "D:/test.txt";
try {
// Serialize序列化
FileOutputStream fos = new FileOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.close();
fos.close();
// Deserialize反序列化
FileInputStream fis = new FileInputStream(path);
ObjectInputStream ois = new ObjectInputStream(fis);
p = (Person) ois.readObject();
ois.close();
fis.close();
System.out.println("decerialize = " + p);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
输出结果
使用ultraEdit查看序列化结果