Java序列化是指将Java中的类对象状态以字节的形式保存,需要的时候可以解码获取,通常用于共享数据交互、网络通信等。在Java中,属于对象的状态才应该保存,因此,静态数据成员不能保存;如果不愿意保存某个变量,可以将此变量声明为transient;另外,并不是所有的对象都可以序列化,系统级的类对象如Thread、OutputStream、Socket等类及其子类对象是不可以序列化的。
要序列化某个对象,只需要类实现java.io.Serializable
接口。如下例子:
1 package de.vogella.java.serilization; 2 3 import java.io.Serializable; 4 5 public class Person implements Serializable { 6 private String firstName; 7 private String lastName; 8 // stupid example for transient 9 transient private Thread myThread; 10 11 public Person(String firstName, String lastName) { 12 this.firstName = firstName; 13 this.lastName = lastName; 14 this.myThread = new Thread(); 15 } 16 17 public String getFirstName() { 18 return firstName; 19 } 20 21 public void setFirstName(String firstName) { 22 this.firstName = firstName; 23 } 24 25 public String getLastName() { 26 return lastName; 27 } 28 29 public void setLastName(String lastName) { 30 this.lastName = lastName; 31 } 32 33 @Override 34 public String toString() { 35 return "Person [firstName=" + firstName + ", lastName=" + lastName 36 + "]"; 37 } 38 39 }
1 package de.vogella.java.serilization; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.ObjectInputStream; 6 import java.io.ObjectOutputStream; 7 8 public class Main { 9 public static void main(String[] args) { 10 String filename = "time.ser"; 11 Person p = new Person("Lars", "Vogel"); 12 13 // Save the object to file 14 FileOutputStream fos = null; 15 ObjectOutputStream out = null; 16 try { // 编码(序列化)的一般形式 17 fos = new FileOutputStream(filename); //定义保存的文件对象 18 out = new ObjectOutputStream(fos); //定义对象输出流对象 19 out.writeObject(p); 20 21 out.close(); 22 } catch (Exception ex) { 23 ex.printStackTrace(); 24 } 25 // Read the object from file 26 // Save the object to file 27 FileInputStream fis = null; 28 ObjectInputStream in = null; 29 try { 30 fis = new FileInputStream(filename); // 解码(反序列化)的一般形式 31 in = new ObjectInputStream(fis); 32 p = (Person) in.readObject(); 33 out.close(); 34 } catch (Exception ex) { 35 ex.printStackTrace(); 36 } 37 System.out.println(p); 38 } 39 }