用于读取/存储500个对象的数据结构

时间:2011-08-25 21:18:55

标签: android xml data-structures

当我的应用程序启动时,我需要从xml页面加载大约500个对象,如下所示:

<object>
<name>objectname</name>
<info>info</info>
<info2>info</info2>
<info3>info</info3>
<info4>info</info4>
<alias>false</alias>
</object>

现在我想将它存储在设备上,希望读数会更快。目前我使用ObjectOutputStream来编写对象。

private static void write(ArrayList<MyObject> objects, String fileName, Context context) {
        final File cacheDir = context.getCacheDir();
        final File objectsFile = new File(cacheDir.getAbsoluteFile() + File.separator + fileName);

        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        boolean keep = true;

        try {
            fos = new FileOutputStream(objectsFile);
            oos = new ObjectOutputStream(fos);

            oos.writeObject(objects);
        } catch (Exception e) {
            e.printStackTrace();
            keep = false;
        } finally {
            try {
                if (oos != null)
                    oos.close();
                if (fos != null)
                    fos.close();
                if (keep == false)
                    objectsFile.delete();
            } catch (Exception e) {
            }
        }
    }

这不是一个非常快速的解决方案,阅读可能需要大约10-15秒。我在列表视图中显示对象,因此需要立即读取所有对象。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我认为存储此类数据的最佳方法是在数据库中(see here)。

解析一次并将信息存储在数据库中(每个属性一列)。从数据库中检索500条记录应该非常快:)

答案 1 :(得分:0)

我假设您不希望每次运行应用程序时都解析XML。我建议使用DataOutputStream并进行自己的编码/解码。它会比ObjectOutputStream快得多。您可以通过写入对象数量的计数来启动文件,因为这样可以更轻松地读取所有内容。

private static void write(ArrayList<MyObject> objects /* , other args */ ) {
    // ...
    try {
        dos = new DataOutputStream(new FileOutputStream(objectsFile));
        dos.writeInt(objects.size());
        for (MyObject object : objects) {
            dos.writeUTF(object.info);
            dos.writeUTF(object.info2);
            dos.writeUTF(object.info3);
            dos.writeUTF(object.info4);
            dos.writeBoolean(object.alias);
        }
        dos.flush();
    } catch (Exception e) {
        e.printStackTrace();
        keep = false;
    } finally {
        try {
            if (dos != null)
                dos.close();
            if (keep == false)
                objectsFile.delete();
        } catch (Exception e) {
        }
    }
}

对于阅读,只需使用DataInputStream遵循相同的模式:

ArrayList<MyObject> read( /* args */ ) {
    // ...
    ArrayList<MyObject> objects = new ArrayList<MyObject>();
    int n = dis.readInt();
    while (n-- > 0) {
        MyObject object = new MyObject();
        object.info = dis.readUTF();
        // etc.
        objects.add(object);
    }
    return objects;
}
相关问题