如何序列化对象并将其保存到Android中的文件?假设我有一些简单的类,一旦它被实例化为一个对象,我希望能够将其内容序列化为一个文件,并通过稍后加载该文件来检索它......我不知道从哪里开始,如何将此对象序列化为文件需要做什么?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中我很新,所以我完全迷失了。
3 回答
倚天杖
TA贡献1828条经验 获得超3个赞
保存(没有异常处理代码):
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);ObjectOutputStream os = new ObjectOutputStream(fos);os.writeObject(this);os.close();fos.close();
加载(没有异常处理代码):
FileInputStream fis = context.openFileInput(fileName);ObjectInputStream is = new ObjectInputStream(fis);SimpleClass simpleClass = (SimpleClass) is.readObject();is.close();fis.close();
沧海一幻觉
TA贡献1824条经验 获得超5个赞
我只是用Generics创建了一个类来处理它,所以它可以用于所有可序列化的对象类型:
public class SerializableManager { /** * Saves a serializable object. * * @param context The application context. * @param objectToSave The object to save. * @param fileName The name of the file. * @param <T> The type of the object. */ public static <T extends Serializable> void saveSerializable(Context context, T objectToSave, String fileName) { try { FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(objectToSave); objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Loads a serializable object. * * @param context The application context. * @param fileName The filename. * @param <T> The object type. * * @return the serializable object. */ public static<T extends Serializable> T readSerializable(Context context, String fileName) { T objectToReturn = null; try { FileInputStream fileInputStream = context.openFileInput(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); objectToReturn = (T) objectInputStream.readObject(); objectInputStream.close(); fileInputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return objectToReturn; } /** * Removes a specified file. * * @param context The application context. * @param filename The name of the file. */ public static void removeSerializable(Context context, String filename) { context.deleteFile(filename); }}
- 3 回答
- 0 关注
- 769 浏览
添加回答
举报
0/150
提交
取消