玩过 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());
}
如果我运行这段代码,我将在控制台中读取一个空文件,如下所示:
Here is the file:
但是如果我将 loopValue
修改为 10000 之类的值,我将得到如下结果:
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
我知道如果我在读取文件之前调用 flush()
或 close()
可以解决这个问题,但为什么会这样呢? PrintWriter
什么时候决定在没有我告诉它的情况下清理它的缓冲区?为什么当我关闭或刷新 PrintWriter
时这个问题不会发生?
谢谢!
最佳答案
PrintWriter
缓冲区背后的一般概念和动机是将某些内容写到控制台的开销很大。因此,通过排队待输出的更改,程序可以更有效地运行。想象一下,您有一个 Java 程序,从 CPU 的角度来看,它正在做一些非常密集的事情,例如多线程应用程序中的繁重计算。然后,如果您还坚持每次调用 PrintWriter.print()
时立即交付其输出,程序可能会挂起,整体性能会下降。
如果您坚持要在调用后立即看到 PrintWriter
的输出,那么您可以调用 flush()
来实现这一点。但如前所述,在某些情况下可能会出现性能损失。
关于java - PrintWriter 什么时候自动打印到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31736725/