Java:从InputStream读取并不总是读取相同数量的数据 [英] Java: Read from InputStream doesn't always read the same amount of data

查看:158
本文介绍了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);

我已经使用它(获得可用大小并直接读取到字节缓冲区的逻辑)
for File I / O没有任何问题,我也用zip文件。但是最近我又进入了一个例子,其中 zipInput.read(content,0,theSize); 实际上读取比 theSize 少3个字节。
$ b

并且由于代码不在循环中检查由 zipInput.read(content,0,theSize)返回的长度; 我读了最后3个字节丢失的文件
,后来程序无法正常运行(文件是一个二进制文件)。



大小不一的zip文件1075字节(在我的情况下有问题的zip条目是867字节)的代码工作正常!

据我所知,代码的逻辑可能不是最好的,但为什么现在突然出现这个问题呢?

如果我立即用一个更大的压缩文件运行程序,那怎么办?



任何输入都非常值得欢迎

谢谢

解决方案

InputStream read API文档:


尝试读取多达len个字节,但可以读取一个较小的数字


...和:


返回:读取到缓冲区中的字节总数,如果
没有更多的数据,因为已经到达流的末尾,则返回-1。

换句话说,除非read方法返回-1,还有更多的数据可以读取,但是你不能保证 read 会正确读 / strong>指定的字节数。指定的字节数是上限,它描述了读取数据的最大数量

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

解决方案

From the InputStream read API docs:

An attempt is made to read as many as len bytes, but a smaller number may be read.

... and:

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.

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.

这篇关于Java:从InputStream读取并不总是读取相同数量的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆