Java:从InputStream读取并不总是读取相同数量的数据
无论好坏,我一直在使用如下代码,没有任何问题:
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 条目运行该程序,它为什么会起作用呢?
非常欢迎任何意见
谢谢
For good or bad I have been using code like the following without any problems:
ZipFile aZipFile = new ZipFile(fileName);
InputStream zipInput = aZipFile.getInputStream(name);
int theSize = zipInput.available();
byte[] content = new byte[theSize];
zipInput.read(content, 0, theSize);
I have used it (this logic of obtaining the available size and reading directly to a byte buffer)
for File
I/O without any issues and I used it with zip files as well.
But recently I stepped into a case that the zipInput.read(content, 0, theSize);
actually reads 3 bytes less that the theSize
available.
And since the code is not in a loop to check the length returned by zipInput.read(content, 0, theSize);
I read the file with the 3 last bytes missing
and later the program can not function properly (the file is a binary file).
Strange enough with different zip files of larger size e.g. 1075 bytes (in my case the problematic zip entry is 867 bytes) the code works fine!
I understand that the logic of the code is probably not the "best" but why am I suddenly getting this problem now?
And how come if I run the program immediately with a larger zip entry it works?
Any input is highly welcome
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从
InputStream
读取
API 文档:... 和:
换句话说,除非 read 方法返回 -1,否则仍有更多数据可供读取,但您不能保证
read
将准确读取指定的字节数。指定的字节数是描述它将读取的最大数据量的上限。From the
InputStream
read
API docs:... and:
In other words unless the read method returns -1 there is still more data available to read, but you cannot guarantee that
read
will read exactly the specified number of bytes. The specified number of bytes is the upper bound describing the maximum amount of data it will read.使用
available()
并不能保证它计算到流末尾
的总可用字节数。参考Java
InputStream
的available()
方法。它说您的问题的示例解决方案如下:
这肯定适用于所有大小的输入文件。
Using
available()
does not guarantee that it counted total available bytes to theend of stream
.Refer to Java
InputStream
'savailable()
method. It says thatAn example solution for your problem can be as follows:
This works for sure on all sizes of input files.
执行此操作的最佳方法应该如下所示:
其中 IOUtils.toByteArray(in) 方法不断读取直到 EOF,然后返回字节数组。
The best way to do this should be as bellows:
where the IOUtils.toByteArray(in) method keeps reading until EOF and then return the byte array.