如何序列化一个对象并将其保存到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中,我非常新,所以我完全失去了。

保存(没有exception处理代码):

 FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(this); os.close(); fos.close(); 

加载(没有exception处理代码):

 FileInputStream fis = context.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fis); SimpleClass simpleClass = (SimpleClass) is.readObject(); is.close(); fis.close(); 

我已经尝试了这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); 

完整的error handling代码和添加的文件streamclosures。 将它添加到你想要能够序列化和反序列化的类中。 在我的情况下,类名是CreateResumeForm 。 你应该把它改成你自己的class级名称。 Android界面Serializable不足以将对象保存到文件,它只创buildstream。

 // Constant with a file name public static String fileName = "createResumeForm.ser"; // Serializes an object and saves it to a file public void saveToFile(Context context) { try { FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(this); objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } // Creates an object by reading it from a file public static CreateResumeForm readFromFile(Context context) { CreateResumeForm createResumeForm = null; try { FileInputStream fileInputStream = context.openFileInput(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); createResumeForm = (CreateResumeForm) objectInputStream.readObject(); objectInputStream.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return createResumeForm; } 

在你的Activity像这样使用它:

 form = CreateResumeForm.readFromFile(this); 

我只是创build了一个类来处理这个与generics,所以它可以用于所有可序列化的对象types:

 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); } }