0

I want to read/write data dictionary in file which is in android internal/external memory. In WP7, they have used IsolatedStorage for storing the dictionary directly. In IOS, they can write NSDictionary directly to the file. Please anyone tell me the way to write DataDictionary into file.

Note: I have the keys and values in the Map variable. how to store this Map directly to file

4

2 回答 2

3

我建议将您的话放入数据库中,原因如下


即使是最不耐烦的用户,使用 SQLite 在 android 上进行数据库查找也“足够快”(~1ms)

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

尝试从“就地”而不是“在
内存中”的文件中读取条目实际上是在尝试解决 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

}
于 2013-01-08T10:23:02.000 回答
0

I'm unsure if using SharedPreferences (link) is something that is suitable for your usecase.

You store via a key-value pair, and can have multiple SharedPreferences per application. While both are stored as String objects, the value can be automatically cast to other primitives using built in methods.

Mark Murphy has written a library, cwac-loaderex (link), to facilitate access of SharedPreferences via the use of the Loader pattern (link), which offsets some of the work you need to do to keep IO off the main thread.

于 2013-01-08T10:20:36.627 回答