2013-01-08 55 views
0

我想讀取/寫入android內部/外部存儲器中的文件中的數據字典。在WP7中,他們使用IsolatedStorage直接存儲字典。在IOS中,他們可以直接將NSDictionary寫入文件。請任何人告訴我將DataDictionary寫入文件的方式。如何以編程方式在android中讀取/寫入數據字典

注意:我在Map變量中有鍵和值。 如何直接存儲這個地圖文件

回答

3

我建議把你的話到數據庫,原因如下

上使用SQLite的Android

DB查找是「不夠快」(〜1毫秒)甚至
最心急的用戶

將大文件讀入內存是 內存有限的環境(如android)中的一種危險操作。

試圖讀出「到位」文件的條目,而不是「在
記憶」有效地試圖解決所有的SQLite
已經解決了你的問題。

Embed a database in the .apk of a distributed application [Android]

您可以通過搜索對象序列

[EDIT 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); 

[EDIT 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) { 

    } 
找到更詳細的示例0

[編輯3]

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

    // check for value 

} 
+0

但是,如果你保存在文件中的鍵值,它的成本太多。我的意思是當你試圖搜索一個詞時,你如何做到這一點? – Talha

+0

雖然存儲我有附加鍵值和值的一些值,所以我可以拆分這 – Ponmalar

+0

我不想在這裏使用SQLite存儲。任何其他選項? – Ponmalar

0

我不確定是否使用SharedPreferenceslink)的東西是適合你的用例。

您通過鍵值對存儲,並且每個應用程序可以有多個SharedPreferences。雖然兩者都存儲爲String對象,但該值可以使用內置方法自動轉換爲其他基元。

馬克·墨菲寫了一個庫,cwac-loaderexlink),便於通過使用Loader模式(link),這抵消了一些你需要做的,讓IO關閉主線程工作的SharedPreferences訪問。

+0

檢查的說明,請 – Ponmalar

相關問題