我正在使用以下代碼來保存和檢索Android和內部存儲器中的對象。我用一個成功的字符串對象測試了它。當我嘗試保存位圖時,出現IOException。 (我發現我必須調用compress方法)所以我注意到我可以保存一些對象,保存對象有什麼限制?某些對象不保存到Android內部存儲器
當我保存一個對象時,它只保存字段嗎?我可以保存包含其他對象的對象嗎?請清除我。
代碼:
public Object readObjectFromMemory(String filename) {
Object defautObject = null;
FileInputStream fis;
try {
fis = game.openFileInput(filename);
ObjectInputStream is = new ObjectInputStream(fis);
defautObject = is.readObject();
is.close();
this.gameEngineLog.d(classTAG, "Object successfully read: " + filename);
}
catch (FileNotFoundException e) {
e.printStackTrace();
this.gameEngineLog.d(classTAG, "FileNotFoundException");
this.gameEngineLog.d(classTAG, "Object couldn't be opened: " + filename);
}
catch (StreamCorruptedException e) {
e.printStackTrace();
this.gameEngineLog.d(classTAG, "StreamCorruptedException");
this.gameEngineLog.d(classTAG, "Object couldn't be opened: " + filename);
}
catch (IOException e) {
e.printStackTrace();
this.gameEngineLog.d(classTAG, "IOException");
this.gameEngineLog.d(classTAG, "Object couldn't be opened: " + filename);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
this.gameEngineLog.d(classTAG, "ClassNotFoundException");
this.gameEngineLog.d(classTAG, "Object couldn't be opened: " + filename);
}
return defautObject;
}
public void writeObjectToMemory(String filename, Object object) {
FileOutputStream fos;
try {
fos = game.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(object);
os.close();
this.gameEngineLog.d(classTAG, "Object successfully written: " + filename);
}
catch (FileNotFoundException e) {
e.printStackTrace();
this.gameEngineLog.d(classTAG, "Object couldn't be written: " + filename);
}
catch (IOException e) {
e.printStackTrace();
this.gameEngineLog.d(classTAG, "Object couldn't be written: " + filename);
}
}
在此先感謝。
當我加載對象時,將標記爲瞬態的對象設置爲null? – 2012-07-10 15:42:57
是的,因爲在Java中沒有其他方式來表達未定義的狀態 – tiguchi 2012-07-10 15:51:33
有沒有辦法保存瞬態數據類型? – 2012-07-10 16:37:36