首先下载XStream-X.X.X.jar包,然后加载到类路径下。例子代码如下:
import java.io.*;
import java.beans.*;
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.*;

public class Test ...{


/** *//**
* @param args
* @throws IOException
* @throws ClassNotFoundException
*/

public static void main(String[] args) throws IOException, ClassNotFoundException ...{
// TODO Auto-generated method stub
jdkReader();
}

public static void xstreamWriter() throws IOException...{
FileWriter fw = new FileWriter("out.xml",true);
XStream xstream = new XStream();
ObjectOutputStream out = xstream.createObjectOutputStream(fw);

out.writeObject(new Person("Joe", "Walnes"));
out.writeObject(new Person("Someone", "Else"));
out.writeObject("hello");
out.writeInt(12345);

out.close();
}

public static void xstreamReader() throws IOException, ClassNotFoundException...{
FileReader fr = new FileReader("out.xml");
XStream xstream = new XStream(new DomDriver());
ObjectInputStream in = xstream.createObjectInputStream(fr);
Person a = (Person)in.readObject();
Person b = (Person)in.readObject();
String c = (String)in.readObject();
int d = in.readInt();
System.out.println(a.getFirstName());
System.out.println(b.getFirstName());
System.out.println(c);
System.out.println(d);
}

public static void jdkWriter() throws FileNotFoundException...{
XMLEncoder e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
e.writeObject(new Person("Hello,","world"));
e.close();
}

public static void jdkReader() throws FileNotFoundException...{
XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("Test.xml")));
Person p = (Person)d.readObject();
d.close();
System.out.println(p.getFirstName());
}
}


public class Person ...{
private String firstName;
private String lastName;

public Person()...{
}

public Person(String afirstName,String alastName)...{
firstName = afirstName;
lastName = alastName;
}

public String getFirstName() ...{
return firstName;
}

public void setFirstName(String firstName) ...{
this.firstName = firstName;
}

public String getLastName() ...{
return lastName;
}

public void setLastName(String lastName) ...{
this.lastName = lastName;
}

}


jdk提供的方法只能对JavaBean对象进行序列化,所以具有局限性,而且只能序列化xxxSetter(),xxxGetter,removeXXX()方法。