第一个项目的学生管理系统用到了HashMap,那么问题来了,怎么把HashMap序列化,io我们知道可以把数据存到文档里,但是HashMap也可以,因为实现了Serializable接口(这个接口就是使得对象实例可以被保存成文件,在后续使用的时候可以直接从文件中把这个对象实例给读出来,对象中的数据还在),于是便有了这篇文章,序列化HashMap,所有实现该接口的类都可以进行序列化。话不多说,上代码:
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class TestSerializable implements Serializable {
static HashMap<String,String> Map1 = new HashMap<>();
static HashMap<Integer,String> Map2 = new HashMap<>();
static HashMap<Integer,Double> Map3 = new HashMap<>();
public static void main(String[] args) throws Exception {
Map1.put("x","y");
Map1.put("键","值");
Map2.put(1,"值1");
Map2.put(5,"值2");
Map3.put(5,6.8/2);
Map3.put(12,21.672653);
serialize();
deserialize();
}
private static void serialize() throws Exception {
for (Map.Entry<String, String> next : Map1.entrySet()) {
System.out.println(next.getKey() + ":" + next.getValue());
}
for (Map.Entry<Integer, String> next : Map2.entrySet()) {
System.out.println(next.getKey() + ":" + next.getValue());
}
for (Map.Entry<Integer, Double> next : Map3.entrySet()) {
System.out.println(next.getKey() + ":" + next.getValue());
}
File file = new File("E:\\新建文件夹\\newfile.txt");
if(!file.exists()){
System.out.println("创建是否成功:"+file.createNewFile());
}
System.out.println("=================开始序列化================");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file.getPath()));
oos.writeObject(Map1);
oos.writeObject(Map2);
oos.writeObject(Map3);
oos.flush();
oos.close();
System.out.println("=================序列化成功================");
}
private static void deserialize() throws Exception {
File file = new File("E:\\新建文件夹\\newfile.txt");
System.out.println("=================开始反序列化================");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file.getPath()));
Map1 = (HashMap<String, String>) ois.readObject();
Map2 = (HashMap<Integer, String>) ois.readObject();
Map3 = (HashMap<Integer, Double>) ois.readObject();
ois.close();
for (Map.Entry<String, String> next : Map1.entrySet()) {
System.out.println(next.getKey() + ":" + next.getValue());
}
for (Map.Entry<Integer, String> next : Map2.entrySet()) {
System.out.println(next.getKey() + ":" + next.getValue());
}
for (Map.Entry<Integer, Double> next : Map3.entrySet()) {
System.out.println(next.getKey() + ":" + next.getValue());
}
}
}
代码解释:首先是实现了Serializable接口,然后创建文件,接着创建ObjectOutputStream对象,ObjectOutputStream通过在流中使用文件可以实现对象的持久存储,接着使用writeObject方法写入文件,然后使用readobject来读取数据,接着用for方法遍历HashMap,然后输出键值对,在类型转换过程中idea一直提示“未检查的转换”,不知道怎么办才能消除这种提示,各位知道的可以在评论区告诉我一下。