gpt4 book ai didi

Java:将HashMap写入文件

转载 作者:行者123 更新时间:2023-11-29 04:57:48 26 4
gpt4 key购买 nike

我正在开发一个将两个单词保存到 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com