java - 序列化 HashMap 并写入文件
问题描述
我有一个HashMap
包含Set<String>
键和值的,
HashMap<Set<String>, Set<String>> mapData = new HashMap<Set<String>, Set<String>>();
如果我想将此HashMap
对象写入文件,Whats 是最好的方法。我也想从那个文件中读回HashMap<Set<String>, Set<String>>
.
解决方案
这是我将映射写入文件并从文件中读回的方法。您可以根据您的用例对其进行调整。
public static Map<String, Integer> deSerializeHashMap() throws ClassNotFoundException, IOException {
FileInputStream fis = new FileInputStream("/opt/hashmap.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Map<String, Integer> map = (Map<String, Integer>) ois.readObject();
ois.close();
System.out.printf("De Serialized HashMap data saved in hashmap.ser");
return map;
}
public static void serializeHashMap(Map<String, Integer> hmap) throws IOException {
FileOutputStream fos = new FileOutputStream("/opt/hashmap.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(hmap);
oos.close();
fos.close();
System.out.printf("Serialized HashMap data is saved in hashmap.ser");
}
推荐阅读
- deep-learning - 是否可以在 FPGA 上训练 YOLO - 对象检测模型?
- javascript - next() 在 Express 4 上不起作用,错误 [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
- docker - launch ElasticSearch in Docker Plesk
- django - Django filter many to many list of objects that contains all the items of a list
- html - 如何通过使 div(及其内容)更小来防止文本中断?
- curl - unexpectedly website returns redirection to itself
- python - Where to get the raw html code in dash/layout/html to print local pdf after executing dash app?
- statistical-test - What statistical test should I use?
- c++ - 多维动态数组的内存丢失
- php - How to draw BarChart with MySQL data in React native?