保存并读取 hashmap 到文件?

Save and read hashmap to file?

我想在 txt 文件中写入和读取此 hashmap。这是我试过的:

主要class:

    SaveRead xd = new SaveRead();
    HashMap <String,Integer>users = new HashMap<String,Integer>();

//e 在开始时被调用

    private Object e() throws ClassNotFoundException, FileNotFoundException, IOException {
        return xd.readFile();
    }

    public void onFinish() {
          try {
            xd.saveFile(users);
        } catch (IOException e) {
        }
    }

//保存读取class:

public class SaveRead implements Serializable{

    public void saveFile(HashMap<String, Integer> users) throws IOException{
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("/Users/Konto/Documents/scores.txt"));
    outputStream.writeObject(users);
}

    public HashMap<String, Integer> readFile() throws ClassNotFoundException, FileNotFoundException, IOException{
        Object ii = new ObjectInputStream(new FileInputStream("/Users/Konto/Documents/scores.txt")).readObject();
        return (HashMap<String, Integer>) ii;
    }
}

这样可以吗?当它尝试读取文件时,我没有得到想要的结果。有没有更好的方法呢?

可能是因为您没有关闭流,所以内容没有刷新到磁盘。您可以使用 try-with-resources statement(在 Java 7+ 中可用)来清理它。这是一个可编译的示例:

public class SaveRead implements Serializable
{
    private static final String PATH = "/Users/Konto/Documents/scores.txt";

    public void saveFile(HashMap<String, Integer> users)
            throws IOException
    {
        try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(PATH))) {
            os.writeObject(users);
        }
    }

    public HashMap<String, Integer> readFile()
            throws ClassNotFoundException, IOException
    {
        try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(PATH))) {
            return (HashMap<String, Integer>) is.readObject();
        }
    }

    public static void main(String... args)
            throws Exception
    {
        SaveRead xd = new SaveRead();

        // Populate and save our HashMap
        HashMap<String, Integer> users = new HashMap<>();
        users.put("David Minesote", 11);
        users.put("Sean Bright", 22);
        users.put("Tom Overflow", 33);

        xd.saveFile(users);

        // Read our HashMap back into memory and print it out
        HashMap<String, Integer> restored = xd.readFile();

        System.out.println(restored);
    }
}

编译并运行这会在我的机器上输出以下内容:

{Tom Overflow=33, David Minesote=11, Sean Bright=22}