【发布时间】:2011-05-31 14:33:27
【问题描述】:
这是我第一次尝试在任何平台上序列化/反序列化对象,委婉地说,我很困惑。
在我的游戏对象实现 Serializable 之后,我将它输出到一个文件中:
public void saveGameState(){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(theGame);//theGame is an instance of the custom class
//TGame which stores game info.
byte[] buf = bos.toByteArray();
FileOutputStream fos = this.openFileOutput(filename,
Context.MODE_PRIVATE);
fos.write(buf);
fos.close();
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
}
File f =this.getDir(filename, 0);
Log.v("FILE",f.getName());
}
这似乎有效,因为我没有引发异常。我只有在反序列化时才能确定。这就是事情变成梨形的地方。
public God loadSavedGame(){
TGame g=null;
InputStream instream = null;
try {
instream = openFileInput(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
return g;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
我从这里Android Java -- Deserializing a file on the Android platform 获得了此代码的基础,并尝试为我的应用程序修改它。跑步时我得到
05-31 23:30:45.493: ERROR/copybit(1279): copyBits failed (Invalid argument)
何时应该加载输出并且保存的游戏从保存时开始。 任何帮助将不胜感激。
【问题讨论】:
标签: android serialization file-io