Momo1199 2012-11-29 01:48 采纳率: 0%
浏览 1960
已采纳

从SD卡中获取多个对象

实现在SD卡中加载多个对象的代码:

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

但是此代码只能加载一个对象。多谢指点。

  • 写回答

1条回答 默认 最新

  • loFataMer 2012-11-29 02:27
    关注

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?