无论好坏,我一直在使用如下代码,没有任何问题:
ZipFile aZipFile = new ZipFile(fileName);
InputStream zipInput = aZipFile.getInputStream(name);
int theSize = zipInput.available();
byte[] content = new byte[theSize];
zipInput.read(content, 0, theSize);
我用过(这种获取可用大小直接读到字节缓冲区的逻辑)
File
I/O 没有任何问题,我也将它用于 zip 文件。
但最近我遇到了一个案例,即 zipInput.read(content, 0, theSize);
实际上读取的字节数比可用的 theSize
少 3 个字节。
并且由于代码不在循环中以检查 zipInput.read(content, 0, theSize);
返回的长度,我读取了缺少最后 3 个字节的文件
后来程序无法正常运行(该文件是二进制文件)。
不同的较大尺寸的 zip 文件足够奇怪,例如1075 字节(在我的例子中,有问题的 zip 条目是 867 字节)代码工作正常!
我知道代码的逻辑可能不是“最好的”,但为什么我现在突然遇到这个问题?
如果我使用较大的 zip 条目立即运行该程序,为什么它会起作用?
非常欢迎任何输入
谢谢
最佳答案
来自 InputStream
read
API 文档:
An attempt is made to read as many as len bytes, but a smaller number may be read.
...和:
Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
换句话说,除非 read 方法返回 -1 否则还有更多数据可供读取,但您不能保证 read
将准确 读取指定的字节数.指定的字节数是描述它将读取的最大数据量的上限。
关于Java:从 InputStream 读取并不总是读取相同数量的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7874713/