到达EOF时,缓冲读取器不会冲洗到缓冲区
我使用读取(缓冲,关闭,LEN)有一个缓冲的读取器。读者正在将TXT文件读为2048个字符的缓冲区。它读取并打印缓冲区中的内容,直到达到末端并返回-1。到那时,它不再将最后一个字符冲入其缓冲区。
每次读取后,我都尝试重置缓冲区,但无济于事。
代码复制。
运行代码时,上次读取时,它不得完全填充缓冲区。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
```
public class bufferRead{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("path to file");
BufferedReader br = new BufferedReader(reader);
char[] buffer = new char[2048];
int off = 0;
int totalNumRead = 0;
int numRead;
while ((numRead = br.read(buffer, off, 2048)) != -1) {
totalNumRead += numRead;
System.out.println(numRead + " " + totalNumRead);
System.out.println(buffer);
}
System.out.println(buffer);
System.out.println(numRead + " " + totalNumRead);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a buffered reader using read(buffer, off, len). The reader is reading a txt file into a buffer of 2048 characters. It reads and prints whats in the buffer fine until it reaches the end and returns -1. At that point it not longer flushes the last characters into its buffer.
Ive tried reseting the buffer after each read to no avail.
Code to reproduce.
When running the code, the last time it reads it must not completely fill the buffer.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
```
public class bufferRead{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("path to file");
BufferedReader br = new BufferedReader(reader);
char[] buffer = new char[2048];
int off = 0;
int totalNumRead = 0;
int numRead;
while ((numRead = br.read(buffer, off, 2048)) != -1) {
totalNumRead += numRead;
System.out.println(numRead + " " + totalNumRead);
System.out.println(buffer);
}
System.out.println(buffer);
System.out.println(numRead + " " + totalNumRead);
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,
br.read(buffer,off,2048)
返回读取的字符数。对于循环的最后一次迭代,numread可能小于
buffer.length.length
sobuffer
将包含最后一排和第二行的字符:但是,如果您更改此字符,它将仅打印每次迭代的内容,因为它将打印值设置为确切的字符数量阅读:
Note that
br.read(buffer, off, 2048)
returns the number of characters read in.For the very last iteration of the loop, numRead might be less than
buffer.length
sobuffer
will contain characters from last AND second last row:But if you change to this, it will only print what was read in for each iteration as it sets the printed value to the exact number of characters read in:
您为什么要缓冲已经缓冲的课程?
Why are you buffering an already buffered class?