我已经试过这2个选项(读/写)与普通的对象,对象的阵列(150个对象),地图:
选项1:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
选项2:
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不便之处在于你必须做出具体的代码读取:
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);
非常有用。你能否解释一下,我们是否需要序列化类作为目标文件进行写入。 – 2012-05-10 09:25:54
如果您使用Serializable接口,则将此功能隐式添加到您的类中。如果你想要的只是简单的对象序列化,那就是我会用到的。这也非常容易实施。 http://developer.android.com/reference/java/io/Serializable.html – mtmurdock 2012-08-09 22:07:11
+1,对于多个对象保存有一个技巧要求:http://stackoverflow.com/a/1195078/1321401 – Luten 2013-10-03 16:39:15