gpt4 book ai didi

android - 为什么 BufferedInputStream.read() 在 Android Nougat 用于返回 0 时返回 -1?

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:04 24 4
gpt4 key购买 nike

在 Android N 设备上测试我的应用程序时,我发现我有许多与我使用 BufferedInputStream 的方式相关的新问题。问题似乎是我如何解释 BufferedInputStream.read() 的返回值。如果返回 0,我假设可以从底层流中读取 0 个字节,如果返回 -1,我假设底层流已经到达文件末尾(并退出读取)。这在牛轧糖之前一直有效。现在,当底层 InputStream.read() 返回 0 时,BufferedInputStream.read() 返回 -1。什么是正确的行为?为什么会这样?

这是一个精炼的例子......

   class ZeroBytesReadInputStream extends InputStream {
...
@Override
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
return 0;
}
}

private int testZeroBytesReadBufferedInputStream() {
InputStream inputStream = new ZeroBytesReadInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int valueReturned = 0;
try {
byte[] toStream = new byte[100];
valueReturned = bufferedInputStream.read(toStream, 0, 100);
Log.d("Zero Bytes Read Test", "BufferedInputStream returned = " + valueReturned + ". Android Version = " + android.os.Build.VERSION.SDK_INT);
} catch (IOException e) {
e.printStackTrace();
}

return valueReturned;
}

运行时的输出 -10-19 09:28:51.970 9138 9138 D 零字节读取测试:BufferedInputStream 返回 = -1。 Android 版本 = 24

10-19 09:32:19.200 12675 12675 D 零字节读取测试:BufferedInputStream 返回 = 0。Android 版本 = 23

最佳答案

根据 InputStream.read(byte[] b, int off, int len) 的文档,该方法实际上不应该返回 0,除非 len 参数为 0:

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

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

因此,底层流的实现是有问题的,因此 BufferedInputStream 的行为是不确定的。

关于android - 为什么 BufferedInputStream.read() 在 Android Nougat 用于返回 0 时返回 -1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40134881/

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