简体   繁体   English

Java:从磁盘写入/读取映射

[英]Java: Writing/Reading a Map from disk

I have a data structure that I would like to be able to write to a file before closing the program, and then read from the file to re-populate the structure the next time the application starts. 我有一个数据结构,我希望能够在关闭程序之前写入文件,然后从文件中读取以在下次应用程序启动时重新填充结构。

My structure is HashMap<String, Object> . 我的结构是HashMap<String, Object> The Object is pretty simple; 对象非常简单; For member variables it has a String, and two small native arrays of type Boolean. 对于成员变量,它有一个String,以及两个Boolean类型的小型本机数组。 This is a real simple application, and I wouldn't expect more than 10-15 <key,value> pairs at one time. 这是一个非常简单的应用程序,我不希望一次超过10-15个<key,value>对。

I have been experimenting (unsuccessfully) with Object input/output streams. 我一直在使用Object输入/输出流进行实验(不成功)。 Do I need to make the Object class Serializable? 我是否需要使Object类可序列化?

Can you give me any suggestions on the best way to do this? 你能给我任何关于最佳方法的建议吗? I just need a push in the right direction. 我只需要朝着正确的方向努力。 Thanks! 谢谢!

EDIT: Well I feel dumb still, I was writing from one map and reading into another map, and then comparing them to check my results. 编辑:嗯,我仍然感到愚蠢,我正在从一张地图写入并阅读另一张地图,然后比较它们以检查我的结果。 Apparently I was comparing them wrong. 显然我在比较他们错了。 Sigh. 叹。

If you aren't concerned about Object particularly , you just need key value pair of String,String then I would suggest you to go for java.util.Properties . 如果你不特别关注Object,你只需要对String,String的键值对,那么我建议你去java.util.Properties otherwise here you go 否则你去吧

        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);
Map m = new HashMap();
// let's use untyped and autoboxing just for example
m.put("One",1);
m.put("Two",2);

ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("foo.ser")
);
oos.writeObject(m);
oos.flush();
oos.close();

Yes, your objects will need to implement Serializable in order to be serialized by the default Java mechanism. 是的,您的对象需要实现Serializable才能通过默认的Java机制进行序列化。 HashMap and String already implement this interface and thus can be serialized successfully. HashMapString已经实现了这个接口,因此可以成功序列化。

Take a look at Sun's own Serialization tutorial - it's quite short and I think should cover everything you need for your simple case. 看一下Sun自己的序列化教程 - 它很简短,我认为应该涵盖简单案例所需的一切。 (You should just be able to serialise the Map object to the stream, and then read it back in on subsequent runs). (您应该只能将Map对象序列化为流,然后在后续运行中将其读回)。

If you do run into problems, try serializing a simple HashMap<String, String> with some dummy values. 如果遇到问题,请尝试使用一些虚拟值序列化一个简单的HashMap<String, String> If this succeeds, you'll know that the problem lies (somehow) with your own class' serializability; 如果这成功了,你就会知道问题在于(以某种方式)你自己的班级'可串行化; alternatively, if this doesn't work you can focus on the basic structure before throwing your own class into the mix. 或者,如果这不起作用,您可以在将自己的类投入混合之前关注基本结构。

Post back if you have any more specific problems that you can't figure out on your own. 如果您有任何您自己无法解决的具体问题,请回发。

Yes, if you want to write an object to the file system, that object must implement Serializeable . 是的,如果要将对象写入文件系统,则该对象必须实现Serializeable Here is a tutorial that should help you out. 是一个应该帮助你的教程。

Don't bother with making it Serializable until you understand more about what that's used for. 在了解更多关于它的用途之前,不要费心去制作Serializable。 You want to look at FileWriter and google "java file io" A good way to write this data is as CSV. 你想看看FileWriter和google“java file io”写这个数据的好方法是CSV。

eg. 例如。

key1,key2,key3 valuea1,valuea2,valuea3 valueb1,valueb2,valueb3 key1,key2,key3 valuea1,valuea2,valuea3 valueb1,valueb2,valueb3

Hope this helps. 希望这可以帮助。

I'd advise against using Serializable ; 我建议不要使用Serializable ; it is much harder to do properly than it first seems. 比起初看起来要难得多。 It would seem that simply adding implements Serializable is all you need to do. 似乎只需添加implements Serializable就可以了。 But in fact this adds many restrictions on your code that are difficult to deal with in practical software development (rather than in school). 但事实上,这增加了对代码的许多限制,这些限制在实际软件开发中很难处理(而不是在学校中)。 To see just how horrible these restrictions are, see the book Effective Java (second edition) by Bloch. 要了解这些限制有多可怕,请参阅Bloch的Effective Java(第二版)一书。

SERIALIZE A HASHMAP: This code is working fine , I have implemented and used in my app. SERIALIZE HASHMAP:这段代码工作正常,我在我的应用程序中实现并使用。 Plz make ur functions accordingly for saving map and retrieving map. Plz相应地制作你的功能以保存地图和检索地图。

Imp thing is, you need to make confirm that the objects you are putting as value in map must be serializable , means they should implement serailizbele interface. 不好的是,您需要确认您在map中作为值放置的对象必须是可序列化的,这意味着它们应该实现serailizbele接口。 ex. 恩。 Map<.String,String> hashmap=new HashMap<.String,String>().. here in this line ...map and string both are implictly serializable , so we dont need to implement serializble for these explicitly but if you put your own object that must be serializable. Map <.String,String> hashmap = new HashMap <.String,String>()..这一行在这一行... 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();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM