首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Android中序列化对象并将其保存为文件?

如何在Android中序列化对象并将其保存为文件?
EN

Stack Overflow用户
提问于 2010-11-08 01:11:50
回答 6查看 150.6K关注 0票数 133

假设我有一些简单的类,一旦它被实例化为对象,我希望能够将其内容序列化为文件,并在以后通过加载该文件来检索它……我不知道从哪里开始,我需要做什么才能将这个对象序列化为文件?

代码语言:javascript
复制
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中这是一个非常简单的任务,但在安卓中我是新手,所以我完全迷失了方向。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-11-08 01:54:31

保存(无异常处理代码):

代码语言:javascript
复制
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

正在加载(无异常处理代码):

代码语言:javascript
复制
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();
票数 254
EN

Stack Overflow用户

发布于 2013-05-08 16:50:30

我已经尝试了这两个选项(读/写),使用普通对象,对象数组(150个对象),Map:

Option1:

代码语言:javascript
复制
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();

Option2:

代码语言:javascript
复制
SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();

选项2的速度是选项1的两倍

选项2的不便之处在于,您必须编写特定的代码来读取:

代码语言:javascript
复制
Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
    events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);
票数 37
EN

Stack Overflow用户

发布于 2015-11-24 22:50:47

我刚刚创建了一个用泛型来处理这个问题的类,所以它可以与所有可序列化的对象类型一起使用:

代码语言:javascript
复制
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);
    }

}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4118751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档