Java:将HashMap写入文件

标签 java file save

我正在开发一个将两个单词保存到 HashMap 中的程序。我需要能够获取 HashMap 键和值并将其以“key:value”格式写入文件。当我的 save() 方法被调用时,HashMap 内容应该被写入文件,该文件的名称作为构造函数的参数给出。如果文件无法保存,该方法返回 false;否则返回真。但是,如果文件不存在,它就不起作用。它也不保存对现有文件所做的更改。我不太了解如何读/写文件...谢谢。

package dictionary;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Scanner;


public class MindfulDictionary {

private HashMap<String, String> words;
private File file;

public MindfulDictionary() {
    this.words = new HashMap<String, String>();
}

public MindfulDictionary(String file) {
    this.file = new File(file);
    this.words = new HashMap<String, String>();
}

public boolean load() {
    try {
        Scanner fileReader = new Scanner(this.file);
        while (fileReader.hasNextLine()) {
            String line = fileReader.nextLine();
            String[] parts = line.split(":");   // the line is split at :

            String word = parts[0];
            String trans = parts[1];
            this.add(word, trans);
        }
    } catch (Exception e) {
        System.out.println("nope");
    }
    return true;
}

public boolean save() {
    boolean saved = true;
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(this.file.getName(), true));
        for (String key : this.words.keySet()) {
            writer.write(key + ":" + this.words.get(key) + "\n");
            writer.newLine();
            writer.flush();
            writer.close();
        }
    } catch (Exception e) {

    }
    return saved;
}

public void add(String word, String translation) {
    if ((!this.words.containsKey(word))) {
        this.words.put(word, translation);
    }
}

public String translate(String word) {
    if (this.words.containsKey(word)) {
        return this.words.get(word);
    } else if (this.words.containsValue(word)) {
        for (String key : this.words.keySet()) {
            if (this.words.get(key).equals(word)) {
                return key;
            }
        }
    }
    return null;
}

public void remove(String word) {
    if (this.words.containsKey(word)) {
        this.words.remove(word);
    } else if (this.words.containsValue(word)) {
        String remove = "";
        for (String key : this.words.keySet()) {
            if (this.words.get(key).equals(word)) {
                remove += key;
            }
        }
        this.words.remove(remove);
    }
}

最佳答案

注意这部分代码,

try {
    writer = new BufferedWriter(new FileWriter(this.file.getName(), true));
    for (String key : this.words.keySet()) {
        writer.write(key + ":" + this.words.get(key) + "\n");
        writer.newLine();
        writer.flush();
        writer.close(); // !!
    }
} catch (Exception e) {

}

在这里,您在 BufferedWriter 对象上调用 close()。在调用 close() 之后,您不能使用该对象。

Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.

阅读更多关于 close() here .

此外,由于您正在捕获所有异常并且未对它们进行任何处理,因此您没有注意到 IOException 。以后永远不要这样做。至少记录发生的任何异常。这将帮助您进行调试。

关于Java:将HashMap写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33115004/

相关文章:

iphone - 应用程序关闭后如何保存变量?

javascript - C#.net 相当于 JS .on()

ios - 保存/加载 IOS 数据

java - 从 DefaultMutableTreeNode 递归删除子项不会在框架中正确更新

java - 我如何初始化通用数组

java - 检查外部文件中是否存在值(java)

java - 从文件中读取单词后,按字母顺序在 java 中创建单词数组

file - 一次将整个文本文件读入 MATLAB 变量

java - Spring-Data 中子对象不与父对象一起获取

java - Spring Security Kerberos、Kerberos + AD - 错误 : Access Denied, 没有可存储的 key