1.保存對象到文件中
Java語言只能將實現了Serializable接口的類的對象保存到文件中,利用如下方法即可:
public static void writeObjectToFile(Object obj)
{
File file =new File("test.dat");
FileOutputStream out;
try {
out = new FileOutputStream(file);
ObjectOutputStream objOut=new ObjectOutputStream(out);
objOut.writeObject(obj);
objOut.flush();
objOut.close();
System.out.println("write object success!");
} catch (IOException e) {
System.out.println("write object failed");
e.printStackTrace();
}
}
參數obj一定要實現Serializable接口,否則會拋出java.io.NotSerializableException異常。另外,如果寫入的對象是一個容器,例如List、Map,也要保證容器中的每個元素也都是實現 了Serializable接口。例如,如果按照如下方法聲明一個Hashmap,並調用writeObjectToFile方法就會拋出異常。但是如果是Hashmap<String,String>就不會出問題,因為String類已經實現了Serializable接口。另外如果是自己創建的類,如果繼承的基類沒有實現Serializable,那么該類需要實現Serializable,否則也無法通過這種方法寫入到文件中。
Object obj=new Object();
//failed,the object in map does not implement Serializable interface
HashMap<String, Object> objMap=new HashMap<String,Object>();
objMap.put("test", obj);
writeObjectToFile(objMap);
2.從文件中讀取對象
可以利用如下方法從文件中讀取對象
public static Object readObjectFromFile()
{
Object temp=null;
File file =new File("test.dat");
FileInputStream in;
try {
in = new FileInputStream(file);
ObjectInputStream objIn=new ObjectInputStream(in);
temp=objIn.readObject();
objIn.close();
System.out.println("read object success!");
} catch (IOException e) {
System.out.println("read object failed");
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return temp;
}
讀取到對象后,再根據對象的實際類型進行轉換即可。