从内部存储中读取ArrayList

时间:2013-06-11 15:08:45

标签: android arraylist storage 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());
    }
}

但我现在要做的是从存储中读取整个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阅读一种方式吗?

1 个答案:

答案 0 :(得分: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
}