2

我有一个 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());
    }
}

但是我现在要做的是从存储中读取整个 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
}

我以前从未用 Android 读过文件,所以我不知道这是否可能。但是有没有一种我可以在我的自定义中阅读的方法ArrayList

4

1 回答 1

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

反序列化对象:

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
} 
于 2013-06-11T15:12:58.803 回答