2014-02-25 31 views
2

我想用下面的代碼導出一個Hashset(整數)到文件,但它似乎不能使用outputStream.write()來做到這一點。在這裏或谷歌似乎沒有任何以前的問題,涵蓋它讓我感到驚訝。如何將Hashset保存到Android中的文件?

時的Hashset在活動定義爲:

HashSet<Integer> set = new HashSet<Integer>(); 

和方法是:

public void savehashset(){ 
    String filename="storedhashset.set"; 
    File storedhashset = new File(getFilesDir(), filename); 
    FileOutputStream outputStream; 
    try { 
     outputStream = openFileOutput(filename, Context.MODE_PRIVATE); 
     outputStream.write(set); 
     outputStream.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
} 
+0

你爲什麼cannnot使用它?你有沒有檢查你的應用程序有權限寫入文件? –

回答

3

您正在嘗試對文件系列化你HashSet。爲了這個目的,你可以使用一個ObjectOutputStream

try { 
     outputStream = openFileOutput(filename, Context.MODE_PRIVATE); 
     ObjectOutputStream oos = new ObjectOutputStream(outputStream); 
     oos.writeObject(set); 
     oos.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
} 

writeObject商務部:

對象寫入流的對象。

+0

感謝您的回答。我能夠使用ObjectInputStream來讀取它嗎?ois = new ObjectInputStream(inputStream); set = ois.readObject();' 看來我無法轉換對象? – Andy

+0

你必須施放它。 – Blackbelt

0

由於HashSet的實現Serializable,你可以試試這個:

ObjectOutputStream output = new ObjectOutputStream(
          new FileOutputStream("object.data")); 

HashSet<Integer> object = new HashSet<Integer>(); 

output.writeObject(object); 
//etc. 

output.close(); 
相關問題