如何序列化一个对象,并将其保存到Android的文件? [英] How do I serialize an object and save it to a file in Android?
问题描述
说我有一些简单的类,一旦它的实例作为一个对象我希望能够将其内容序列化到一个文件中,并加载该文件在一段时间后恢复了...我不知道在哪里从这里开始,做什么我需要做的,这个对象序列化到一个文件?
Say I have some simple class and once it's instantiated as an object I want to be able to serialize its contents to a file, and retrieve it by loading that file at some later time... I'm not sure where to start here, what do I need to do to serialize this object to a file?
public class SimpleClass {
public string name;
public int id;
public void save() {
/* wtf do I do here? */
}
public static SimpleClass load(String file) {
/* what about here? */
}
}
这大概是世界上最简单的问题,因为这是在.NET中一个非常简单的任务,但在Android的我是pretty的新的,所以我完全失去了。
This is probably the easiest question in the world, because this is a really simple task in .NET, but in Android I'm pretty new so I'm completely lost.
推荐答案
保存(W / O异常处理code):
Saving (w/o exception handling code):
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
装载(W / O异常处理code):
Loading (w/o exception handling code):
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();
这篇关于如何序列化一个对象,并将其保存到Android的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!