添加 XStream 支援
按照下列步驟向建立的項目添加 XStream 庫:
1. 在 Eclipse 的 Project Explorer 中選擇建立的項目,從 Project 菜單中選擇 Properties(如 圖 5 所示)。
圖 5. 添加 XStream 庫
2. 單擊 Add External JARs,從 xstream_home/lib 檔案夾中選擇 xstream-1.2.2.jar.
3. 單擊 OK 結束(如 圖 6 所示)。
圖 6. 完成 XStream 支援的添加
圖 7 顯示了添加 XStream 支援後的項目。
序列化對象
這個簡單的例子示範了如何使用 XStream 序列化/逆序列化對象,包括兩個類:Writer 和 Reader。Writer 類使用 XStream API 把 Employee 類型的對象序列化為 XML 並儲存到檔案中(如 清單 1 所示)。
清單 1. Writer.java
package com.samples;import java.io.FileNotFoundException;import java.io.FileOutputStream;import com.thoughtworks.xstream.*;public class Writer { public static void main(String[] args) { Employee e = new Employee(); //Set the properties using the setter methods //Note: This can also be done with a constructor. //Since we want to show that XStream can serialize //even without a constructor, this approach is used. e.setName("Jack"); e.setDesignation("Manager"); e.setDepartment("Finance"); //Serialize the object XStream xs = new XStream(); //Write to a file in the file system try { FileOutputStream fs = new FileOutputStream("c:/temp/employeedata.txt"); xs.toXML(e, fs); } catch (FileNotFoundException e1) { e1.printStackTrace(); } }}
Reader 類讀取該檔案,逆序列化 XML 並把資料裝入 Java 對象(如 清單 2 所示)。
引用自:http://java.chinaitlab.com/XMLBeans/777336_2.html