[英]PrintWriter not printing texts to .txt file
该程序要求输出文件名,似乎工作正常。 直到我尝试使用文本编辑器或终端打开输出文件。 然后我在那个文件中看不到任何空白文件。 此程序创建文本文件但文件为空。 感谢您的帮助。
import java.util.*;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Writes a Memo file.
*
*/
public class MemoPadCreator {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
System.out.print("Enter Output file name: ");
String filename = console.nextLine();
try {
PrintWriter out = new PrintWriter(filename);
boolean done = false;
while (!done) {
System.out.println("Memo topic (enter -1 to end):");
String topic = console.nextLine();
// Once -1 is entered, memo's will no longer be created.
if (topic.equals("-1")) {
done = true;
console.close();
}
else {
System.out.println("Memo text:");
String message = console.nextLine();
/* Create the new date object and obtain a dateStamp */
Date now = new Date();
String dateStamp = now.toString();
out.println(topic + "\n" + dateStamp + "\n" + message);
}
}
/* Close the output file */
} catch (IOException exception) {
System.out.println("Error processing the file:" + exception);
}console.close();
}
}
使用out.flush()
将内容刷新到文件中。
或者使用PrintWriter的自动刷新构造函数( 可能不是最佳性能选项 ),但无论如何都是一个选项
public PrintWriter(Writer out,boolean autoFlush)
autoFlush - 布尔值; 如果为
true
,则println
,printf
或format方法将刷新输出缓冲区
您尚未关闭PrintWriter
对象。 您需要关闭流以在控制台或文件上反映它(取决于您的outputStream)
out.close();
即使你有
PrintWriter out = new PrintWriter(System.out);
...
...
...
out.close();
然后你需要关闭它,以便输出写在控制台上。
因此,在您关闭流的情况下,将写入文件。
您需要刷新PrintWriter
以从内存缓冲区中将要写入文件的内容。
out.flush();
在任何情况下,您还应始终关闭(释放)资源,否则锁定可以或将保留在文件中,具体取决于操作系统。 而close()
也会自动刷新更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.