gpt4 book ai didi

java - 我无法向我自制的 txt 文件写入内容

转载 作者:行者123 更新时间:2023-12-01 13:32:08 24 4
gpt4 key购买 nike

我第一次尝试将自己的 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){
}
}

感谢您的宝贵时间

最佳答案

当您写入 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();
}
}
}

关于java - 我无法向我自制的 txt 文件写入内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21511968/

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