持久化就是将内存中的数据保存起来,使之可以长期存在。在JAVA中,我们可以把JAVA对象直接保存在文件中,在需要使用的时候,直接从文件中读取,这也是对象持久化的一种方式,在这一篇博客中,将演示两种将JAVA对象持久化到文件的方法,直接上代码:
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
/**
* JAVA对象持久化
*
* @author jianggujin
*
*/
public class JavaSerializable
{
/**
* 持久化为XML对象
*
* @param obj
* @param out
*/
public void storeXML(Object obj, OutputStream out)
{
XMLEncoder encoder = new XMLEncoder(out);
encoder.writeObject(obj);
encoder.flush();
encoder.close();
}
/**
* 从XML中加载对象
*
* @param in
* @return
*/
public Object loadXML(InputStream in)
{
XMLDecoder decoder = new XMLDecoder(in);
Object obj = decoder.readObject();
decoder.close();
return obj;
}
/**
* 持久化对象
*
* @param obj
* @param out
* @throws IOException
*/
public void store(Object obj, OutputStream out) throws IOException
{
ObjectOutputStream outputStream = new ObjectOutputStream(out);
outputStream.writeObject(obj);
outputStream.flush();
outputStream.close();
}
/**
* 加载对象
*
* @param in
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public Object load(InputStream in) throws IOException,
ClassNotFoundException
{
ObjectInputStream inputStream = new ObjectInputStream(in);
Object obj = inputStream.readObject();
inputStream.close();
return obj;
}
public static void main(String[] args) throws Exception
{
String storeName = "java object";
File xmlFile = new File("xmlFile.dat");
JavaSerializable serializable = new JavaSerializable();
serializable.storeXML(storeName, new FileOutputStream(xmlFile));
System.out.println(serializable.loadXML(new FileInputStream(xmlFile)));
File file = new File("file.dat");
serializable.store(storeName, new FileOutputStream(file));
System.out.println(serializable.load(new FileInputStream(file)));
}
}
运行结果:
java object
java object
我们可以打开示例中生成的两个文件:
xmlFile.dat <?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_45" class="java.beans.XMLDecoder">
<string>java object</string>
</java>
file.dat