1.简介
在Java中,把对象存储成文件的过程叫序列化,反过来,从文件读取对象叫做反序列化。
2.代码演示
以下代码演示了,如何序列化和反序列化的过程:
public class Main {public static void main(String[] args) throws Exception {
//数据源File dataFile = new File("/Users/jojo/IdeaProjects/data/obj.dat");ObjectOutputStream objectOut = null;//导出用FileOutputStream out = null;//导出用FileInputStream in = null;//导入用ObjectInputStream objectIn = null;//导入用try {//把对象写入到文件的过程:序列化out = new FileOutputStream(dataFile);objectOut = new ObjectOutputStream(out);MyClass myClass = MyClass myClass();//只有添加了Serializable接口的类,才能在写文件时,进行序列化操作objectOut.writeObject(myClass);//写入myClass对象到文件objectOut.flush();//刷新//从文件读取对象的过程:反序列化in = new FileInputStream(dataFile);objectIn = new ObjectInputStream(in);Object o = objectIn.readObject();System.out.println(o);} catch (Exception e) {throw new RuntimeException(e);} finally {if (objectOut != null) {try {objectOut.close();//关闭文件} catch (IOException e) {throw new RuntimeException(e);}}}}
}class MyClass implements Serializable{//序列化的类必须有Serializable接口}