Java序列化之6: 附录2自定义的序列化过程
Java序列化之六: 附录2自定义的序列化过程
import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 2356129180978015792L; private String name; private int age; public Person() { } public Person(String str, int n) { System.out.println("Inside Person's Constructor"); name = str; age = n; } String getName() { return name; } int getAge() { return age; } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import com.thoughtworks.xstream.*; public class Serialize { public static void main(String[] args) { Serialize ser = new Serialize(); ser.serializeToXml(); ser.deSerializeFromXml(); } public void serializeToXml(){ Person[] myPerson = new Person[2]; myPerson[0] = new Person("Jay",24); myPerson[1] = new Person("Tom",23); XStream xstream = new XStream(); try { FileOutputStream fos = new FileOutputStream("E:\\workspace\\2010_03\\src\\myPerson.xml"); xstream.toXML(myPerson,fos); } catch (FileNotFoundException ex) { ex.printStackTrace(); } System.out.println(xstream.toXML(myPerson)); } public void deSerializeFromXml(){ XStream xs = new XStream(); Person[] myPerson = null; try { FileInputStream fis = new FileInputStream("E:\\workspace\\2010_03\\src\\myPerson.xml"); myPerson=(Person[])xs.fromXML(fis); if (myPerson != null) { int len = myPerson.length; for (int i=0;i<len;i++) { System.out.println(myPerson[i].getName()); System.out.println(myPerson[i].getAge()); } } } catch (FileNotFoundException ex) { ex.printStackTrace(); } } }