Java InputStream读取缓冲区 [英] Java InputStream read buffer
问题描述
说我正试图从Java InputStream读取这样的内容:
Say I'm trying to read from a Java InputStream like this:
ZipInputStream zis = new ZipInputStream(new FileInputStream("C:\\temp\\sample3.zip"));
zis.getNextEntry();
byte[] buffer2 = new byte[2];
int count = zis.read(buffer2));
if(count != -1) //process...
else...//something wrong, abort
我正在解析一个二进制文件,在这种情况下,我将缓冲区设置为2,因为我想读取下一个简短内容.如果要读取下一个int等等其他类型的数据,我会将缓冲区的大小设置为4.问题是,即使我知道有足够的未读数据来填充缓冲区,有时zis.read(buffer)也不会填充缓冲区.我可以简单地将整个文件内容转储到数组中并进行解析,但是随后我最终实现了自己的流读取器来执行此操作,这似乎是在重新发明轮子.我还可以实现一个read()函数来检查读取计数,如果小于buffersize,则请求更多数据来填充缓冲区,但这效率低下且难看.有更好的方法吗?
I'm parsing a binary file and I set my buffer to 2 in this case because I want to read the next short. I would set my buffer to size 4 if I want to read the next int and so on for other types. The problem is that sometimes zis.read(buffer) won't fill the buffer even when I know that there is enough unread data to fill the buffer. I could simply dump the entire file contents into an array and parse that, but then I end up implementing my own stream reader to do that which seems like re-inventing the wheel. I could also implement a read() function that checks the read count and if less than buffersize, request more data to fill the buffer, but that's inefficient and ugly. Is there a better way to do this?
这是此处发布的问题的后续问题:
This is a follow-up question to a question posted here:
推荐答案
有更好的方法吗?
Is there a better way to do this?
好吧... ZipInputStream
最终继承自InputStream
,因此您应该能够先用BufferedInputStream
然后用DataInputStream
包装它,并使用readShort
,readInt
等读取数据.
Well ... a ZipInputStream
ultimately inherits from InputStream
so you should be able to wrap it with a BufferedInputStream
and then a DataInputStream
and read data using readShort
, readInt
and so on.
类似这样的东西:
while (zis.getNextEntry() != null) {
DataInputStream dis = new DataInputStream(new BufferedInputStream(zis));
boolean done = false;
do {
short s = dis.readShort();
int i = dis.readInt();
...
} while (!done);
}
注意:您不应该关闭dis
流,因为那样会导致zis
被关闭. (显然,zis
需要在外部关闭,以避免资源泄漏.)
NB: you shouldn't close the dis
stream as that would cause the zis
to be closed. (Obviously, the zis
needs to be closed at an outer level to avoid a resource leak.)
堆栈中的BufferedInputStream
确保您不会在基础流上进行很多小读取工作……这很糟糕.
The BufferedInputStream
in the stack ensures that you don't do lots of small reads on the underlying stream ... which would be bad.
唯一可能的陷阱是它的方法对二进制数据的表示方式有特殊的想法;例如数字是bigendian.如果这是一个问题,请考虑将整个zip条目读取到一个字节数组中,并将其包装在ByteBuffer
中.
The only possible gotcha is that its methods have particular ideas about how the binary data is represented; e.g. numbers are bigendian. If that is an issue, consider reading the entire zip entry into a byte array, and wrapping it in a ByteBuffer
.
这篇关于Java InputStream读取缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!