序列化就是将对象的状态转化为保持或可传输的过程。与序列化相反的就是反序列化了,它将流转换为对象,在这两个过程结合起来,可以轻松的存储和传输数据。
序列化成一般的文件,将被序列化的对象Person:
package com.nuftont.testserializable; import java.io.Serializable; public class Person implements Serializable { private String name; private int age; public Person() { } public Person(String str, int i) { System.out.println("Inside Persion's Constructor!"); name = str; age = i; } String getName() { return name; } int getAge() { return age; } }
反序列化Person对象,将流转化为对象的过程:
package com.nuftont.testserializable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Java的序列化以及反序列化 * @author Yao * */ public class SerializToFlatFile { public static void main(String[] arg) { SerializToFlatFile stf = new SerializToFlatFile(); stf.saveData(); stf.restoreData(); } public void saveData() { Person myPersion = new Person("Jag", 31); try { FileOutputStream fileOutputStream = new FileOutputStream( "H:\\Test\\myPerson.txt"); ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream); System.out.println("Person Name:" + myPersion.getName()); System.out.println("Person Age:" + myPersion.getAge()); oos.writeObject(myPersion); oos.flush(); oos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void restoreData() { try { FileInputStream fileInputStream = new FileInputStream( "H:\\Test\\myPerson.txt"); ObjectInputStream ois = new ObjectInputStream(fileInputStream); Person mRestorePerson = (Person) ois.readObject(); System.out.println("\n-----------------------\n"); System.out.println("Person Jag, Age: 31"); System.out.println("Name:" + mRestorePerson.getName()); System.out.println("Age:" + mRestorePerson.getAge()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
在H:\Test文件夹下产生myPerson.txt的同时,也在控制台上输出如下信息:
Inside Persion's Constructor! Person Name:Jag Person Age:31 ----------------------- Person Jag, Age: 31 Name:Jag Age:31