hashmap写入文件
时间: 2024-01-15 17:19:48 浏览: 26
要将多个HashMap写入文件并能够单个存取,可以使用Java的序列化和反序列化机制来实现。首先,将多个HashMap对象存储到一个List中,然后将整个List对象进行序列化并写入文件。当需要单个存取时,可以将整个List对象从文件中反序列化出来,并根据需要获取其中的HashMap对象。
以下是一个示例代码:
```java
import java.io.*;
import java.util.*;
public class HashMapFileIO {
public static void main(String[] args) {
List<HashMap<String, Integer>> hashMapList = new ArrayList<>();
// 添加多个HashMap对象到List中
HashMap<String, Integer> hashMap1 = new HashMap<>();
hashMap1.put("key1", 1);
hashMap1.put("key2", 2);
hashMapList.add(hashMap1);
HashMap<String, Integer> hashMap2 = new HashMap<>();
hashMap2.put("key3", 3);
hashMap2.put("key4", 4);
hashMapList.add(hashMap2);
// 将List对象序列化并写入文件
try {
FileOutputStream fileOut = new FileOutputStream("hashmap.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(hashMapList);
out.close();
fileOut.close();
System.out.println("HashMap写入文件成功!");
} catch (IOException e) {
e.printStackTrace();
}
// 从文件中读取并反序列化List对象
List<HashMap<String, Integer>> readHashMapList = null;
try {
FileInputStream fileIn = new FileInputStream("hashmap.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
readHashMapList = (List<HashMap<String, Integer>>) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 单个存取HashMap对象
if (readHashMapList != null) {
HashMap<String, Integer> hashMap = readHashMapList.get(0);
System.out.println("从文件中读取的HashMap对象:");
System.out.println(hashMap);
}
}
}
```
运行以上代码,将会在当前目录下生成一个名为"hashmap.ser"的文件,其中存储了多个HashMap对象。通过反序列化,可以将这些HashMap对象读取出来,并进行单个存取。