Read an ArrayList from Internal Storage

风格不统一 提交于 2019-11-28 01:56:42

问题


I have an Android application and I would like to read and write an ArrayList<MyClass> to the Internal Storage.

The writing part works (I believe, haven't tested it yet :-) ) :

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

But what I want to do now is read the whole ArrayList from the Storage and return it as an ArrayList like so:

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
}

I've never read in a file with Android before, so I don't know if this is even possible. But is there A way I can read in my custom ArrayList?


回答1:


you have to serialize/deserialize your object:

Your MyClass must implments Serializable and all the member inside MyClass must be serializable

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

to deserialize the object:

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
} 


来源:https://stackoverflow.com/questions/17047537/read-an-arraylist-from-internal-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!