2011-11-22 73 views
1

我寫了這個函數,它會試圖存儲映射,但它不工作,我想?我正在使用netbeans,每次我到java src中的項目目錄時,我找不到創建的文件或項目中的任何其他位置。這張地圖無疑是有效的,因爲當我沒有處理存儲時,輸出會變得完美。順便說一句我不落實seriliazable :)Java序列化映射到文件

注:地圖類型TreeMap的

public boolean storeMap(TreeMap<DateTime, Integer> map){ 
    try{ 
    f_out = new FileOutputStream("mapObject.data"); 
    obj_out = new ObjectOutputStream (f_out); 
    obj_out.writeObject(map); 
    return true; 
    }catch(IOException ioe){ 
     System.err.print(ioe); 
     return false; 
    } 
} 

的有爲什麼不是生成的輸出文件的一個原因? 感謝

+0

嘗試刷新輸出,並關閉它。 – Sid

+1

你應該總是關閉你的流,添加'f_out.close();'在你的'迴歸真實'之前。 – pushy

+0

我剛剛做了,src文件夾裏沒有任何東西改變 –

回答

1

我建議使用絕對路徑,這就是說,

f_out = new FileOutputStream("/home/username/mapObject.data"); 

或Windows

f_out = new FileOutputStream("c:\\work\\mapObject.data"); 

如果沒有(System.err.print(ioe);這條線沒有打印任何東西)拋出異常,然後該文件是在某處創建的。

+0

完美!做到了!我認爲它會假設當前的工作目錄並在那裏存儲:)欣賞它 –

0

嘗試爲outputStreams調用fulsh()方法。

obj_out.flush(); 
    f_out.flush(); 

並在最後的表述中關閉它們。

+1

close()會刷新,所以在close()之前調用flush()本身是不必要的。 –

+0

是的,你是對的)) – shift66

1

SERIALIZE HASHMAP: 此代碼工作正常,我已經實現並在我的應用程序中使用。 Plz使你的功能相應地保存地圖和檢索地圖。

重要的是,您需要確認您在映射中放置爲值的對象必須是可序列化的,意味着它們應該實現serailizbele接口。恩。 Map < .String,String> hashmap = new HashMap < .String,String>()..在這一行中... map和string都是隱式可序列化的,所以我們不需要爲這些明確地實現可串行化,但是如果你把你自己的對象必須是可序列化的。


public static void main(String arr[]) 
{ 
    Map<String,String> hashmap=new HashMap<String,String>(); 
hashmap.put("key1","value1"); 
    hashmap.put("key2","value2"); 
    hashmap.put("key3","value3"); 
    hashmap.put("key4","value4"); 

    FileOutputStream fos; 
    try { 
     fos = new FileOutputStream("c://list.ser"); 

    ObjectOutputStream oos = new ObjectOutputStream(fos); 
    oos.writeObject(hashmap); 
    oos.close(); 

    FileInputStream fis = new FileInputStream("c://list.ser"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 
    Map<String,String> anotherList = (Map<String,String>) ois.readObject(); 

    ois.close(); 

    System.out.println(anotherList); 

} catch (FileNotFoundException e) {e.printStackTrace(); 
} catch (IOException e) {e.printStackTrace(); 
    } catch (ClassNotFoundException e) {e.printStackTrace(); 
    } 

}