[英]Why data not be written to File when use PrintWriter?
我正在与PrintWriter
一起将数据写入文件,但没有按预期工作。 程序构建成功,但是数据未输出到文件。 这是我的代码:
File source = new File("notebook.txt");
PrintWriter out = new PrintWriter(source);
out.print("I hate Mondays");
当我尝试使用另一种方式创建PrintWriter
对象时,如下所示:
File source = new File("notebook.txt");
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(source)));
out.print("I love Fridays");
我不明白PrintWiter
构造函数有什么区别。 为什么第一个块没有将数据输出到文件?
您必须刷新PrintWriter
才能将数据写入文件。 您可以either by explicitly call the
close method or use the
try-with-resource`语句来关闭PrintWriter来实现此目的:
File source = new File("notebook.txt");
try (PrintWriter out = new PrintWriter(source)) {
out.print("I hate Mondays");
}
或者,您可以不使用try-with-resource
语句使用它:
PrintWriter out = new PrintWriter(source);
out.print("I hate Mondays");
out.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.