我有一个名为“sortMap”的树形图,其中包含一些具有各自值的键。我正在尝试将树状图写入文本文件,如下所示。
String aggFileName = "agg-"+String.valueOf("06.txt");
FileWriter fstream = new FileWriter(aggFileName);
BufferedWriter out = new BufferedWriter(fstream);
for (Map.Entry<String, String> entry : sortMap.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); //this statement prints out my keys and values
out.write(entry.getKey() + "\t" + entry.getValue());
System.out.println("Done");
我面临的问题是,尽管我的代码中的打印语句显示我成功地迭代了树状图,但我最终得到了一个空白文件。我可能做错了什么?
最佳答案
写入文件时,所有写入操作完成后需要刷新并关闭文件。大多数情况下,只需调用 close() 就足够了,但如果您希望每次迭代结束时更改在文件中可用,则需要在 IO 对象上调用lush() 函数。
大多数 IO 对象都有一个缓冲区,它是一个临时空间,用于存储写入的任何值。当刷新该缓冲区时,它们将内容写入正在使用的流中。您的代码应如下所示:
String aggFileName = "agg-"+String.valueOf("06.txt");
FileWriter fstream = new FileWriter(aggFileName);
BufferedWriter out = new BufferedWriter(fstream);
for (Map.Entry<String, String> entry : sortMap.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); //this statement prints out my keys and values
out.write(entry.getKey() + "\t" + entry.getValue());
System.out.println("Done");
out.flush(); // Flush the buffer and write all changes to the disk
}
out.close(); // Close the file
关于Java - 将树状图写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30470031/