我第一次尝试将自己的txt写入特定目录中的文件。 test.mod文件已正确放置,但是当我打开文件时它是空的并且不包含任何文本。 我在这里错过了什么?
public static void main(String[] args) {
String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive";
File bestand = new File(pad + "\\test.mod");
try {
BufferedWriter pen = new BufferedWriter(new FileWriter(bestand));
pen.write("line1");
pen.write("line2");
}catch(IOException e){
}
}
感谢您的时间
答案 0 :(得分:1)
当您写入BufferedWriter
时,您(可能)正在写入内存缓冲区,并且您必须flush()
写入以确保它们到达磁盘。 close()
也会在任何合理的实施中隐含地调用flush()
,但依赖它并不是一个好习惯:
public static void main(String[] args) {
String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive";
File bestand = new File(pad + "\\test.mod");
BufferedWriter pen = null;
try {
pen = new BufferedWriter(new FileWriter(bestand));
pen.write("line1");
pen.write("line2");
pen.flush();
}catch(IOException e){
// Probably should have some treatment here too
}
finally {
if (pen != null) {
pen.close();
}
}
}