问题描述
我有一个Android应用程序,我想读,写的的ArrayList< MyClass的>
的内部存储
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());
}
}
但我想从存储现在要做的就是阅读整个ArrayList和回击像这样一个ArrayList
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
}
我从来没有读过之前与Android的文件,所以我不知道这甚至有可能。但是,有没有办法,我可以在我的自定义读的ArrayList
?
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
?
推荐答案
您必须序列化/反序列化对象:
you have to serialize/deserialize your object:
您MyClass的必须implments序列化和里面所有MyClass的成员必须是可序列化
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
}
这篇关于阅读从内部存储一个ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!