/*
* Java对象持久化工具类
* 这个类提供将Java对象持久化到XML文件,从XML文件 读取Java对象两种功能。
* 注意使用前需要在构件路径里添加xstream-1.2.2.jar 和 xpp3_min-1.1.3.4.O.jar
*/
public class Persistence
{
private static XStream xStream = new XStream();
//从指定的路径xml文件读取对象
public static Object readObjFromXMLFile(String filePath)
{
InputStream is = null;
try
{
is = new FileInputStream(filePath);
return xStream.fromXML(is);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
//将指定的对象写到指定路径的xml文件中
public static void writeObjectToXMLFile(Object obj, String filePath)
{
OutputStream out = null;
try
{
out = new FileOutputStream(filePath);
xStream.toXML(obj, out);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
//将xml 字符串转换为对象
public static Object readObjFromXMLString(String xml)
{
return xStream.fromXML(xml);
}
//将对象转换成 xml形式的字符串
public static String writeObjToXMLString(Object obj)
{
return xStream.toXML(obj);
}
}