Java 如何将 HashMap 读取和写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3347504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read and write a HashMap to a file?
提问by lisam
I have the following HashMap:
我有以下HashMap:
HashMap<String,Object> fileObj = new HashMap<String,Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist",cols);
I write it to a file as follows:
我将其写入文件如下:
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.flush();
Now I want to read this file back to a HashMap where the Object is an ArrayList. If i simply do:
现在我想把这个文件读回一个 HashMap,其中对象是一个 ArrayList。如果我只是这样做:
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
fileObj = (HashMap<String,Object>)s.readObject();
s.close();
This does not give me the object in the format that I saved it in.
It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?
这不会以我保存它的格式为我提供对象。它返回一个包含 15 个空元素和 < mylist,[a,b,c] > 对的表,位于第三个元素。我希望它只返回一个具有我最初提供给它的值的元素。
//如何将同一个对象读回 HashMap ?
OK So based on Cem's note: This is what seems to be the correct explanation:
好的 所以基于 Cem 的注释:这似乎是正确的解释:
ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object. If you want it to serialize in the format that you desire you should write your own serializer/deserializer.
ObjectOutputStream 以 ObjectInputStream 能够理解的任何格式序列化对象(在本例中为 HashMap),并且通常对任何 Serializable 对象执行此操作。如果您希望它以您想要的格式序列化,您应该编写自己的序列化器/反序列化器。
In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).
就我而言:当我从文件中读取对象并获取数据并对其进行任何我想做的事情时,我只是简单地遍历 HashMap 中的每个元素。(它只在有数据的地方进入循环)。
Thanks,
谢谢,
回答by Hbas
I believe you′re making a common mistake. You forgot to close the stream after using it!
我相信你犯了一个常见的错误。使用后忘记关闭流!
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
回答by aarestad
Your first line:
你的第一行:
HashMap<String,Object> fileObj = new HashMap<String,Object>();
gave me pause, as the values are not guaranteed to be Serializable
and thus may not be written out correctly. You should really define the object as a HashMap<String, Serializable>
(or if you prefer, simpy Map<String, Serializable>
).
让我停下来,因为不能保证这些值是Serializable
正确的,因此可能无法正确写出。您应该真正将对象定义为 a HashMap<String, Serializable>
(或者,如果您愿意,可以将其定义为simpy Map<String, Serializable>
)。
I would also consider serializing the Map in a simple text format such as JSON since you are doing a simple String -> List<String>
mapping.
我还会考虑以简单的文本格式(例如 JSON)序列化 Map,因为您正在进行简单的String -> List<String>
映射。
回答by Stephen
I believe you're getting what you're saving. Have you inspected the map before you save it? In HashMap
:
我相信你得到了你所节省的。您在保存地图之前检查过地图吗?在HashMap
:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
e.g. the default HashMap
will start off with 16 null
s. You use one of the buckets, so you only have 15 null
s left when you save, which is what you get when you load.
Try inspecting fileObj.keySet()
, .entrySet()
or .values()
to see what you expect.
例如,默认值HashMap
将从 16null
秒开始。您使用其中一个存储桶,因此null
保存时只剩下 15秒,这就是您加载时得到的。尝试检查fileObj.keySet()
,.entrySet()
或者.values()
看看你期望什么。
HashMap
s are designed to be fast while trading off memory. See Wikipedia's Hash tableentry for more details.
HashMap
s 被设计为在牺牲内存的同时速度很快。有关更多详细信息,请参阅维基百科的哈希表条目。
回答by Peter Lawrey
You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.
您似乎将 HashMap 的内部重新表示与 HashMap 的行为方式混淆了。集合是一样的。这是一个简单的测试来证明给你看。
public static void main(String... args)
throws IOException, ClassNotFoundException {
HashMap<String, Object> fileObj = new HashMap<String, Object>();
ArrayList<String> cols = new ArrayList<String>();
cols.add("a");
cols.add("b");
cols.add("c");
fileObj.put("mylist", cols);
{
File file = new File("temp");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(fileObj);
s.close();
}
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();
Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
Assert.assertEquals(fileObj.toString(), fileObj2.toString());
Assert.assertTrue(fileObj.equals(fileObj2));
}
回答by SURENDRANATH SONAWANE
you can also use JSON file to read and write MAP object.
您还可以使用 JSON 文件来读取和写入 MAP 对象。
To write map object into JSON file
将地图对象写入 JSON 文件
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Suson");
map.put("age", 26);
// write JSON to a file
mapper.writeValue(new File("c:\myData.json"), map);
To read map object from JSON file
从 JSON 文件中读取地图对象
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
new File("c:\myData.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
and import ObjectMapper from com.fasterxml.Hymanson and put code in try catch block
并从 com.fasterxml.Hymanson 导入 ObjectMapper 并将代码放入 try catch 块中