简体   繁体   中英

How to get multiple objects from SD card in Android?

How do I load multiple objects in Android from SD card?

I got this:

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

but this only loads a singe object from the SD card.

I am thinking something like ArrayList<Dog> dogs = in.readAllObjects() , but this code will only come true in my dreams.

Code samples will be appreciated.

From readObjects() documentation:

Reads the next object from the source stream.

So I recommend using a loop to read every dog:

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

I don't know if dog will ever be null of the top of my head, but it will definitely throw an exception if in tries to read past the end of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM