即使您没有传递一个缓冲区,Java 扫描器是否也会隐式创建一个缓冲区?

发布于 2024-08-02 15:26:07 字数 527 浏览 2 评论 0原文

如果我有以下示例文件,其中每个数字代表一个字节(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哀由 2024-08-09 15:26:07

java.util.Scanner 代码中:

// Internal buffer used to hold input
private CharBuffer buf;

// Size of internal character buffer
private static final int BUFFER_SIZE = 1024; // change to 1024;

Yes.

From the java.util.Scanner code:

// Internal buffer used to hold input
private CharBuffer buf;

// Size of internal character buffer
private static final int BUFFER_SIZE = 1024; // change to 1024;
风铃鹿 2024-08-09 15:26:07

这并不明显,但是如果你仔细查看 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文