即使您没有传递一个缓冲区,Java 扫描器是否也会隐式创建一个缓冲区?
如果我有以下示例文件,其中每个数字代表一个字节(123 有字节 1、2 和 3):
123456789
假设我创建一个 FileInputStream。这将逐字节读取二进制文件。所以 .read() 返回 1,然后返回 2,等等。现在假设我创建了一个缓冲区。它读入的初始块(如果我正确理解缓冲区)是 1-5。这使得它不仅可以逐字节读取,还可以读取整行字符等。但是如果我再次点击 .read() ,我会从 6 开始,而不是 BufferedReader 停止的地方(所以如果 3 是换行符,我告诉 BufferedReader 打印第一行,它打印 1-2,然后使用 FileInputStream 中的 .read() 给我 6,而不是 3。)
为了能够通过分隔符解析数据,扫描仪是否隐式创建一个缓冲区,就像 BufferedReader 创建缓冲区一样,以便它可以找到换行符等?如果我将一个单独的 FileInputStream 传递到扫描仪中,使用 .read() 将不会打印扫描仪找到的第一个分隔符后面的第一个字节,而是打印扫描仪所采用的“块”的末尾?
If I have the following example file where each number is represents a byte (123 has bytes 1, 2, and 3):
123456789
Let's say I create a FileInputStream. This reads in the binary byte by byte. So .read() returns 1, then 2, etc. Now let's say I create a buffer. The initial chunk it reads in (if I understand buffers correctly) is 1-5. This allows it to not only read in byte by byte, but in the case of characters whole lines, etc. But if I hit .read() again, I start at 6, and NOT where the BufferedReader stopped (so if 3 is a line break, and I told the BufferedReader to print the first line, it prints 1-2, and then using .read() from the FileInputStream gives me 6, and not 3.)
In order to be able to parse data by the delimiter, does a Scanner implicitly create a buffer like how a BufferedReader creates a buffer so that it can find line breaks, etc? And if I pass a separate FileInputStream into the Scanner, using .read() will NOT print the first byte following the first delimiter the scanner found, but rather at the end of the "chunk" the scanner took?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是。
从
java.util.Scanner
代码中:Yes.
From the
java.util.Scanner
code:这并不明显,但是如果你仔细查看 Scanner 的 API 文档,你会发现它是基于
Readable
接口 - 该接口中唯一的方法是基于缓冲区的。所以是的,扫描仪隐式创建了一个缓冲区。It's not obvious, but if you look at the API doc of Scanner carefully, you see that it's based on the
Readable
interface - and the only method in that interface is based on a buffer. So yes, Scanner implicitly creates a buffer.