【问题标题】:How do I save and multiple objects from a single file?如何从单个文件中保存多个对象?
【发布时间】:2012-06-29 07:19:42
【问题描述】:

我希望我的应用在本地存储多个对象以供以后使用。

现在,我的问题是我知道如何通过获取整个文件 (federations.dat) 从 ObjectInputStream 加载对象。有没有办法让我从“federations.dat”加载object WHERE id = N?还是我必须为每个对象创建单独的文件?

这是我的加载方法:

public static Object load(Context ctx, String filename) throws FileNotFoundException 
{
    Object loadedObj = null;
    InputStream instream = null;

    instream = ctx.openFileInput(filename);

    try {
        ObjectInputStream ois = new ObjectInputStream(instream);
        loadedObj = ois.readObject();
        return loadedObj;
        
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

有什么建议吗?

【问题讨论】:

标签: java android objectinputstream


【解决方案1】:

你可以这样使用它..

ArrayList<Object> arrayList = new ArrayList<Object>();

Object obj = null;

while ((obj = ois.readObject()) != null) {
    arrayList.add(obj);
}

你可以在你的方法上返回一个 ArrayList。

return arrayList;

编辑: 完整的代码是这样的..

public static ArrayList<Object> load(Context ctx, String filename) 
{
    InputStream fis = null;
    ObjectInputStream ois = null;

    ArrayList<Object> arrayList = new ArrayList<Object>();

    Object loadedObj = null;
    try {
        fis = ctx.openFileInput(filename);
        ois = new ObjectInputStream(fis);

        while ((loadedObj = ois.readObject()) != null) {
             arrayList.add(loadedObj);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (null != ois) ois.close();
        if (null != fis) fis.close();
    }

    return arrayList;
}

希望对你有帮助..

【讨论】:

  • 如果我没记错的话,这会使 ois 在抛出异常时保持打开状态。我的OOP类提倡使用两个嵌套try,外层捕获异常,内层只有一个关闭ois的finally。
  • 会是.. 我只是对@litemode 的代码进行了必要的编辑。这是开发商必须解决的问题。但无论如何,这是一个很好的收获..
  • 另外,第一次从 ois 读取对象时,它似乎被丢弃了。
【解决方案2】:

对@Jan 代码的扩展,修复了在抛出异常时保持ois 打开的问题,以及一些小问题。

public static ArrayList<Object> load(Context ctx, String filename) throws FileNotFoundException {
    InputStream instream = ctx.openFileInput(filename);

    ArrayList<Object> objects = new ArrayList<Object>();

    try {
        ObjectInputStream ois = new ObjectInputStream(instream);
        try{
            Object loadedObj = null;
            while ((loadedObj = ois.readObject()) != null) {
                objects.add(loadedObj);
            }

            return objects;
        }finally{
            ois.close();
        }

    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2022-01-19
    相关资源
    最近更新 更多