从内部存储中读取ArrayList

Han*_* Vn 2 storage android arraylist fileinputstream

我有一个Android应用程序,我想读取和写入ArrayList<MyClass>内部存储.

写作部分工作(我相信,尚未测试它:-)):

ArrayList<MyClass> aList;

    public void saveToInternalStorage() {
    try {
        FileOutputStream fos = ctx.openFileOutput(STORAGE_FILENAME, Context.MODE_PRIVATE);
        fos.write(aList.toString().getBytes());
        fos.close();
    }
    catch (Exception e) {
        Log.e("InternalStorage", e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

但我现在要做的是从存储中读取整个ArrayList并将其作为ArrayList返回,如下所示:

public ArrayList<MyClass> readFromInternalStorage() {
        ArrayList<MyClass> toReturn;
        FileInputStream fis;
        try {
            fis = ctx.openFileInput(STORAGE_FILENAME);

            //read in the ArrayList
            toReturn = whatever is read in...

            fis.close();
        } catch (FileNotFoundException e) {
            Log.e("InternalStorage", e.getMessage());
        } catch (IOException e) {
            Log.e("InternalStorage", e.getMessage()); 
        }
        return toReturn
}
Run Code Online (Sandbox Code Playgroud)

我以前从未在Android文件中读过,所以我不知道这是否可能.但是我有一种方式可以阅读我的习惯ArrayList吗?

Bla*_*elt 5

你必须序列化/反序列化你的对象:

您的MyClass必须使用Serializable,MyClass中的所有成员都必须是可序列化的

 public void saveToInternalStorage() {
        try {
            FileOutputStream fos = ctx.openFileOutput(STORAGE_FILENAME, Context.MODE_PRIVATE);
            ObjectOutputStream of = new ObjectOutputStream(fos);
            of.writeObject(aList);
            of.flush();
            of.close();
            fos.close();
        }
        catch (Exception e) {
            Log.e("InternalStorage", e.getMessage());
        }
}
Run Code Online (Sandbox Code Playgroud)

反序列化对象:

public ArrayList<MyClass> readFromInternalStorage() {
    ArrayList<MyClass> toReturn;
    FileInputStream fis;
    try {
        fis = ctx.openFileInput(STORAGE_FILENAME);
        ObjectInputStream oi = new ObjectInputStream(fis);
        toReturn = oi.readObject();
        oi.close();
    } catch (FileNotFoundException e) {
        Log.e("InternalStorage", e.getMessage());
    } catch (IOException e) {
        Log.e("InternalStorage", e.getMessage()); 
    }
    return toReturn
} 
Run Code Online (Sandbox Code Playgroud)