gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:33:00 25 4
gpt4 key购买 nike

通常我在处理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. 抛出异常:没有返回值,当方法异常返回并出现异常时。

关于java - 如果读取字节数为 0,是否有任何理由继续读取 InputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67568249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com