通常我在处理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.
所以四种可能的情况是:
b
是一个长度为0的byte[]
,所以返回0b
并返回该数字。https://stackoverflow.com/questions/67568249/