日期:2014-05-16 浏览次数:20402 次
public class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	
	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;
	}
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
}下面为三种格式转换的代码:
1.默认格式.
public class SerializeToFlatFile {
	public static void main(String[] args) {
		SerializeToFlatFile ser = new SerializeToFlatFile();
		ser.savePerson();
		ser.restorePerson();
	}
	
	public void savePerson(){
		Person myPerson = new Person("Jay", 24);
		try{
			FileOutputStream fos = new FileOutputStream("E:\\person.txt");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			System.out.println("Person--Jay,24---Written");
			
			oos.writeObject(myPerson);
			oos.flush();
			oos.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("resource")
	public void restorePerson(){
		try{
			FileInputStream fls = new FileInputStream("E:\\person.txt");
			ObjectInputStream ois = new ObjectInputStream(fls);
			
			Person myPerson = (Person)ois.readObject();
			System.out.println("\n---------------------\n");
			System.out.println("Person --read:");
			System.out.println("Name is:"+myPerson.getName());
			System.out.println("Age is :"+myPerson.getAge());
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
输出结果: sr test.serializable.Person I ageL namet Ljava/lang/String;xp t Jay
2.XML格式
//参考:http://www.cnblogs.com/bluesky5304/archive/2010/04/07/1706061.html
public class SerializeXML {
	public static void main(String[] args) {
		SerializeXML ser = new SerializeXML();
		ser.serializeToXml();
		ser.deSerializeFromXml();
	}
	public void serializeToXml(){
		Person[] myPersons = new Person[2];
		myPersons[0] = new Person("Jay", 24);
		myPersons[1] = new Person("Tom", 23);
		
		XSt