1
我正在研究將兩個單詞保存到HashMap中的程序。我需要能夠獲取HashMap鍵和值,並將其作爲「key:value」格式寫入文件。當我的save()方法被調用時,HashMap的內容應該被寫入到名字被作爲參數賦給構造函數的文件中。如果文件無法保存,則該方法返回false;否則它返回true。但是,如果文件不存在,則不起作用。它也不會保存對現有文件所做的更改。我不理解如何讀取/寫入文件太好......謝謝。Java:將HashMap寫入文件
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);
}
}
}
在'save()'中,不要默默地忽略'Exception'。將'e.printStackTrace()'放在'catch'塊中,看看是否有異常。 –
另外,不要在for循環中調用'writer.close()'。把它放在for循環的大括號之後。 (或者,更好的是,查看[try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)塊)。 –
如果你「不理解如何讀/寫文件太好」,把這個程序放在一邊,寫一些簡單的程序,只是寫入文件並讀取它們。在沒有HashMap的情況下進行整理。 –