This question already has answers here:
Serialize multiple different objects single in Java
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
我有两个HashMap

public static HashMap<String, Date> taskMap = new HashMap<String, Date>();
private HashMap<String,String> passMap = new HashMap<String, String>();


和一个只能读取第一个地图的方法

private void readData() {
    try {
        FileInputStream fileIn = new FileInputStream("data/tasks.ser");
        ObjectInputStream ois = new ObjectInputStream(fileIn);
        taskMap.putAll((HashMap)ois.readObject());
        ois.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}


我想知道是否有一种方法可以在单个文件中写入两个HashMap,然后能够读取它们两者以使其更高效。

最佳答案

是的,只需将它们都写入ObjectOutputStream,然后以相同的顺序从ObjectInputStream中读取它们。

09-26 13:31