我一直在尝试迭代HashMap,然后将HashMap中的键写入文件。
这就是我一直在做的事情
HashMap<String,Integer> myHashMap = new Hashmap<String,Integer>();
myHashMap.put(aString,1)
myHashMap.put(bString,2)
myHashMap.put(cString,3)
//..
private void doStuff(){
try {
// Create new file
String path = "myCreatedTxt.txt";
File file = new File(path);
// If file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (Map.Entry<String,Integer> dic : myHashMap.entrySet())
{
System.out.println(dic.getKey() + "/" + dic.getValue());
bw.write(dic.getKey()+"");
}
// Close connection
bw.close();
} catch (IOException x) {
System.out.println(x);
}
}
但是当调用doStuff()时,虽然创建了一个名为myCreatedTxT的文件,但它是空的。
我希望得到的结果如下:
---inside myCreatedFile.txt---
1 11 4 2 5 6 7
在我尝试过的方式之前,我只能在文件上写一个密钥,但这还不够,因为我需要每个密钥。
我想听听一些建议或解释
感谢。
P.S当然,doStuff()在finally {}块的程序中的某个地方被调用。
答案 0 :(得分:1)
我为此示例创建了Writer
类:
public class Writer {
private Map<String, Integer> myHashMap;
public Writer() {
myHashMap = new HashMap<>();
myHashMap.put("a", 1);
myHashMap.put("b", 2);
myHashMap.put("c", 3);
}
public void doStuff() {
try {
// Create new file
final String path = "myCreatedTxt.txt";
File file = new File(path);
// If file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
myHashMap.entrySet().forEach(x -> {
try {
bw.write(x.getKey() + " ");
} catch (IOException e) {
System.out.println("error accord");
}
});
// Close connection
bw.close();
} catch (IOException x) {
System.out.println(x);
}
}
}
并从我的main
课程中调用它:
public class Main {
public static void main(String[] args) {
Writer writer = new Writer();
writer.doStuff();
}
}
我的输出文件看起来完全像:
a b c
那应该做的工作