【发布时间】:2015-07-31 01:30:22
【问题描述】:
在玩了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 时不会发生这个问题?
谢谢!
【问题讨论】:
-
请查看下面给出的答案。
标签: java