介紹
Java序列化是指把Java對象轉換爲字節序列的過程(可以直接以二進制的形式寫入文件,也可以進行網絡傳輸);而Java反序列化是指把字節序列恢復爲Java對象的過程。
應用場景
- 我們都知道,在進行網絡傳輸或者進程間通信的時候,有時候需要傳輸文件,視頻,音頻等,它們都是以二進制的形式進行傳輸,那麼對象也是可以進行傳輸的,這就應用了序列化.
- 再一個,正常情況下,一個對象的生命週期是從new實例開始到程序結束或者被垃圾回收程序回收,那麼有沒有一種情況可以將對象永久保存在硬盤中呢,這就要使用序列化了,將對象以二進制的形式寫入文件中,這個過程也叫對象的持久化.
實現
序列化之前要讓類實現Serializable接口,這個接口是一個空接口,爲的是作爲一個標記,說明這個類實例的對象可以進行序列化,同時,最好還是增加一個序列化UID
先定義個學生類
Student.java
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String birth;
public Student(String id, String name, String birth) {
super();
this.id = id;
this.name = name;
this.birth = birth;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return birth;
}
public void setGender(String birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", birth=" + birth + "]";
}
}
序列化
/**
*
* @功能:將對象序列化
* @時間:2017年3月6日 下午1:59:15
* @throws IOException
*/
public static void outputObject() throws IOException {
List<Student> list = new ArrayList<>();
list.add(new Student("111", "mali1", "jj"));
list.add(new Student("222", "mali2", "hut"));
list.add(new Student("333", "mali3", "gfgd"));
OutputStream out = new FileOutputStream("source\\object", true);
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(list);
oos.flush();
oos.close();
out.close();
}
反序列化
/**
*
* @功能:將對象反序列化
* @時間:2017年3月6日 下午1:59:28
* @throws IOException
* @throws ClassNotFoundException
*/
public static void inputObject() throws IOException, ClassNotFoundException {
FileInputStream in = new FileInputStream("source\\object");
ObjectInputStream ois = new ObjectInputStream(in);
@SuppressWarnings("unchecked")
List<Student> list = (ArrayList<Student>) ois.readObject();
ois.close();
in.close();
for (Object object : list) {
System.out.println(((Student) object).getId() + "," + ((Student) object).getName() + ","
+ ((Student) object).getGender());
}
}