如何序列化对象并将其保存到 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 中我很新,所以我完全迷失了.
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.
推荐答案
保存(无异常处理代码):
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();
加载(无异常处理代码):
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屋!