Java序列化映射到文件

时间:2011-11-22 10:47:59

标签: java treemap

我写了这个函数,它会尝试存储地图,但我觉得它不起作用?我正在使用netbeans,每次我去java src中的项目目录时都无法找到创建的文件或项目中的任何其他位置。地图肯定是有效的,因为当不处理存储时输出完美。顺便说一句,我实施了seriliazable:)

注意:地图的类型为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;
    }
}

是否有原因导致未生成输出文件? 感谢

3 个答案:

答案 0 :(得分:1)

我建议使用绝对路径,就像

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

或在Windows上

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

如果没有抛出异常(System.err.print(ioe);此行没有打印任何内容)则该文件是在某处创建的。

答案 1 :(得分:1)

SERIALIZE HASHMAP: 这段代码工作正常,我在我的应用程序中实现和使用。 Plz相应地制作你的功能以保存地图和检索地图。

重要的是,您需要确认您在map中作为值放置的对象必须是可序列化的,这意味着它们应该实现serailizbele接口。恩。 地图&LT; .String,字符串&GT; hashmap = new HashMap&lt; .String,String&gt;()..这一行在这一行... map和string都是可隐式序列化的,所以我们不需要为这些显式实现serializble但是如果你把你自己的对象必须是可序列化的


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();
    }

}

答案 2 :(得分:0)

尝试为outputStreams调用fulsh()方法。

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

并在最后的陈述中关闭它们。