问题
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