如何从 SD 卡加载 Android 中的多个对象?
我明白了:
ObjectInput in;
Dog dog = null;
try
{
in = new ObjectInputStream(new FileInputStream("/mnt/sdcard/somelocation/save.data"));
dog = (Dog) in.readObject();
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
但这只会从 SD 卡加载单个对象。
我在想类似 ArrayList<Dog> dogs = in.readAllObjects()
的东西,但这个代码只会在我的梦想中实现。
代码示例将不胜感激。
最佳答案
来自 readObjects()
文档:
Reads the next object from the source stream.
所以我建议使用一个循环来读取每只狗:
List<Dog> dogs = new ArrayList<Dog>();
Dog dog;
try {
in = new ObjectInputStream(new FileInputStream("/mnt/sdcard/somelocation/save.data"));
while((dog = (Dog) in.readObject()) != null)
dogs.add(dog);
in.close();
}
// catch the exceptions
我不知道 dog
是否会成为我头顶的 null
,但如果 in
它肯定会抛出异常> 尝试读取文件末尾。
关于android - 如何从 Android 中的 SD 卡获取多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616386/