java - 如果读取字节数为 0,是否有任何理由继续读取 InputStream?

通常我在处理InputStream时,停止读取的条件是读取的字节数小于等于0

例如,

InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
}

但是,当我查看InputStream的文档时

https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[])

只有我注意到

-1 if there is no more data because the end of the stream has been reached.

我在想,我是否应该将我的代码重构为

InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
    if (len > 0) {
        out.write(buf, 0, len);
    }
}

是否会检查 while ((len = in.read(buf)) > 0) 是否会导致任何不需要的错误?

最佳答案

由于 read 被指定为阻塞直到数据可用,它返回 0 的唯一方法是如果您输入的缓冲区的长度为 0(这将成为一个非常无用的缓冲区)。

参见 the JavaDoc :

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte.

所以四种可能的情况是:

  1. b是一个长度为0的byte[],所以返回0
  2. 输入数据可用:非零字节将被读入 b 并返回该数字。
  3. 检测到文件结尾:将返回-1
  4. 抛出异常:没有返回值,当方法异常返回并出现异常时。

https://stackoverflow.com/questions/67568249/

相关文章:

python - 检查是否存在与列表中的字符串匹配的子字符串

c++ - char a[n][m] 和 char a[][m] 有区别吗?

c++ - 如何使函数能够接受原始指针作为迭代器?

node.js - 如何使用 NestJS 为多个国家/地区编写调度程序 12 :00AM(will

c - 学习C——测试数据类型

visual-studio-code - 代码行数旁边的竖线是什么

haskell - 在 haskell 中给 `_` 一个类型签名

kubernetes - 如何将 kubernetes 的一个 secret 值复制到同一 name

amazon-web-services - 为什么 X-Forwarded-Proto 在 Elas

javascript - 如何在一组 span 元素之后替换纯文本内容或文本节点?