inputstream.read 在 java 中读取了多少数据

How much data does inputstream.read reads in java

我在看inputstream对象的read方法的定义,我很困惑每次读了多少数据,因为它说"reads some bytes"

public int read(byte[] b)
         throws IOException
Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

假设我有一个大小为 200 的缓冲区数组,输入流中的数据为 100 字节。是否保证 inputStream.read 获取全部 100 个字节?

虽然从 InputStream 和具体实现(参见 throws IOException 部分)读取时保证 nothing,但是,是的,如果您有一个缓冲区,其size 大于读取的数据,应将所有数据读入缓冲区,缓冲区中剩余的 bytes 不会被写入,因此保持默认原始值 0.

当从 InputStream 管道传输到 OutputStream 时,这也是一个警告。

read 方法 returns 流结束时 byte 读取或 -1 的数量。

这会指示 您需要为 "exact copy".

写入多少 缓冲区

文档here

InputStream 是一个 抽象 class(不是 "object")。因此,它仅指定了一个 接口 ,而不是 实现 ,因此实现细节取决于您使用的实际非抽象子 class。

这个接口的全部要点(或者准确地说:抽象class):你可以绝对不依赖假设 读取了多少字节。您 总是总是总是 必须检查该方法的 return 值才能知道。

背景:这个接口有很多不同的实现。有些是我的缓冲区,有些可能不是。一些读取 "fixed" 输入(可能来自内存中的现有数据)。有人可能会决定给你一个转向互联网的流,下载一个 10 GB 的文件,然后开始一个字节一个字节地发送给你。

你唯一知道的是:方法returns

the total number of bytes read into the buffer

故事结束。

没有。没有保证。 read(byte b[]) 简单地委托给带有三个参数 read(byte b[], int off, int len)read 方法,如下所示:

return read(b, 0, b.length);

该方法的文档如下:

Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.