在使用PrintWriter和文件后,我怀疑为什么有时当我在创建文件时立即读取文件时,存在不一致之处,例如:
File file = new File("Items.txt");
int loopValue = 10;
try {
PrintWriter fout = new PrintWriter(file);
for (int i = 0; i < loopValue; i++) {
fout.print(i + " asdsadas" + System.lineSeparator());
}
//fout.flush(); <-- I know if I call flush or close this problem don't occur
//fout.close();
System.out.println("Here is the file:");
Scanner readFile = new Scanner(file);
while (readFile.hasNext()) {
System.out.println(readFile.nextLine());
}
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)
如果我运行此代码,我将在控制台中读取一个空文件,如下所示:
Here is the file:
Run Code Online (Sandbox Code Playgroud)
但是如果我修改为loopValue10000之类的东西,我会有这样的东西:
Here is the file:
0 asdsadas
1 asdsadas
2 asdsadas
...
... continues
...
9356 asdsadas
9357 asdsadas
9358 <--- here ends, note that it doesnt end in the value 9999
Run Code Online (Sandbox Code Playgroud)
我知道,如果我打电话flush()或close()在阅读文件之前我可以摆脱这个问题,但为什么会这样呢?什么时候PrintWriter确定是时候清理它的缓冲区而不告诉它什么时候?为什么当我关闭或冲洗PrintWriter这个问题时不会发生?
谢谢!
缓冲区背后的一般概念和动机PrintWriter是,将某些内容写入控制台的成本很高。因此,通过将待输出的更改排队,程序可以更有效地运行。想象一下,您有一个 Java 程序,从 CPU 的角度来看,它正在执行一些非常密集的操作,例如多线程应用程序中的繁重计算。然后,如果您还坚持每次调用PrintWriter.print()立即传递其输出,则程序可能会挂起,并且整体性能会下降。
PrintWriter如果您坚持要在调用后立即看到输出,那么您可以调用flush()来实现此目的。但正如已经提到的,在某些情况下可能会出现性能损失。
| 归档时间: |
|
| 查看次数: |
411 次 |
| 最近记录: |