如何序列化對象并將其保存到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 關注
- 800 瀏覽
添加回答
舉報
0/150
提交
取消