如何读/写数据字典在android编程



我想读/写数据字典的文件,这是在android内部/外部存储器。在WP7中,他们使用IsolatedStorage直接存储字典。在IOS中,他们可以直接将NSDictionary写入文件。谁能告诉我如何把DataDictionary写入文件?

注意:我在Map变量中有键和值。如何将此Map直接存储到文件

我建议把你的话录入数据库,原因如下

在android上使用SQLite查找数据库"足够快"(~1ms),甚至
最不耐烦的用户

将大文件读入内存是一种危险的做法内存有限的环境,如android。

尝试从"in place"而不是"in
"文件中读取条目内存"有效地解决了SQLite
已经为你解决了

在分布式应用程序的。apk中嵌入数据库[Android]

您可以通过搜索对象序列化

找到更详细的示例(编辑1)

Map map = new HashMap();
map.put("1",new Integer(1));
map.put("2",new Integer(2));
map.put("3",new Integer(3));
FileOutputStream fos = new FileOutputStream("map.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(map);
oos.close();
FileInputStream fis = new FileInputStream("map.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Map anotherMap = (Map) ois.readObject();
ois.close();
System.out.println(anotherMap);
[编辑2]

try {
        File file = new File(getFilesDir() + "/map.ser");
        Map map = new HashMap();
        map.put("1", new Integer(1));
        map.put("2", new Integer(2));
        map.put("3", new Integer(3));
        Map anotherMap = null;
        if (!file.exists()) {
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(map);
            oos.close();
            System.out.println("added");                
        } else {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            anotherMap = (Map) ois.readObject();
            ois.close();
            System.out.println(anotherMap);
        }

    } catch (Exception e) {
    }
(编辑3)

Iterator myVeryOwnIterator = meMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
    String key=(String)myVeryOwnIterator.next();
    String value=(String)meMap.get(key);
     // check for value
}

我不确定使用SharedPreferences(链接)是否适合您的用例。

通过键值对存储,每个应用程序可以有多个SharedPreferences。虽然两者都存储为String对象,但可以使用内置方法自动将值强制转换为其他原语。

Mark Murphy写了一个库,cwac-loaderex(链接),通过使用Loader模式(链接)来方便访问SharedPreferences,这抵消了一些你需要做的工作,以保持IO远离主线程。

最新更新