java - PrintWriter 不将文本打印到文件
问题描述
我的任务是将一个文件的文本复制到另一个文件。使用以下代码,我可以将文件的行打印到控制台,但无法打印到输出文件。
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File inputFile = new File(input.nextLine());
PrintWriter out = new PrintWriter("/Users/jonathanzier/Dropbox/IdeaProjects/CSE_205_Homework1/src/com/company/output.txt");
input = new Scanner(inputFile);
while (input.hasNextLine()) {
out.println(input.nextLine());
//System.out.println(input.nextLine()); - This will print
//correctly to the console
}
out.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
}
解决方案
打印写入器使用缓冲写入器。它不会立即写入磁盘。当您调用println
、printf
或format
方法时,如果启用了自动刷新,它将写入磁盘。否则,您必须调用flush
方法来写入磁盘。通常调用close
方法应该将缓冲区中的任何内容写入文件而不需要flush
方法。
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html
推荐阅读
- html - 如何将 :nth-child 用于交替行
- npm - 如何在 macOS 中离线配置和使用无服务器?
- elasticsearch - 如何为 ES 批量 API 形成 JSON
- java - 使用 Apache Poi 从 Excel 创建对象
- javascript - 如何将逗号分隔的字符串作为参数传递给 Mongo Script?
- c# - 使用 c# 计算开始和停止时钟的总计数
- ios - 如何使用 SwiftUI 绘制圆弧?
- jenkins - 在 Jenkins 中,是否可以使用类别进行参数选择?
- javascript - 试图在javascript中将对象数组转换为对象
- ansible - ARM 模板部署对已经运行的 MemSQL 实例的影响