ZipInputStream不报告读取的“实际"(即压缩)字节 [英] ZipInputStream doesn't report *actual* (i.e. compressed) bytes read

查看:343
本文介绍了ZipInputStream不报告读取的“实际"(即压缩)字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜欢这个网站!我的问题如下:

Love this website! My issue is as follows:

我正在读取来自HTTP"PUT"请求通过网络发送的zip文件.请求标头告诉我Content-Length为1Mb.以下代码创建ZipInputStream,并将zip内容保存到当前目录中的文件中:

I'm reading a zip file that's coming over a network from an HTTP "PUT" request. The request header tells me that the Content-Length is (say) 1Mb. The following code creates the ZipInputStream, and saves the zip contents to files in the current directory:

ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry ze;
long totalBytesRead = 0;
while ((ze = zis.getNextEntry()) != null) {
    BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(ze.getName()));
    byte[] buffer = new byte[4096];
    int i;
    while ((i = zis.read(buffer)) != -1) {
        totalBytesRead+=i;
        outStream.write(buffer,0,i);
    } 
    outStream.close();
}
inputStream.close();

说完所有内容后,totalBytesRead大约等于1.5Mb(取决于文件的压缩程度,不过可能是任何东西!).我想知道的是,是否有办法找出从原始inputStream中读取了多少实际字节? ze.getSize()ze.getCompressedSize()都为每个压缩条目返回-1(即不知道).我需要此信息作为进度条,以显示已从网络上读取了多少个已传输的zip文件字节.

When all is said and done, totalBytesRead is equal to about 1.5Mb (depending on compression of the files, could be anything though!). What I'd like to know is if there is a way to find out how many actual bytes have been read from the original inputStream? Both ze.getSize() and ze.getCompressedSize() return -1 for every zipped entry (i.e. it doesn't know). I need this info for a progress bar to show how many bytes of the transmitted zip file have been read off the network.

建议?我是否应该子类化ZipInputStream并尝试找出从包装好的InputStream中读取了多少字节?

Suggestions? Should I perhaps subclass ZipInputStream and try to find out how many bytes it's reading from it's wrapped InputStream?

提前谢谢!

推荐答案

当然,这很合理.

基本上有两种选择:读取所有字节,将它们存储(在内存或文件中),对它们进行计数,然后将其解压缩;或对它们进行计数.前者效率低下,而后者将需要InputStream的子类,该子类具有对读取的字节进行计数的能力.我想不出标准库中的哪一个,但是可能在那里存在实现-然后,再次编写自己的实现会很容易.

There are basically two options: read all the bytes, store them (in memory or a file), count them, then decompress them; or count them as they come in. The former seems inefficient, and the latter will require a subclass of InputStream which has the ability to count the bytes it reads. I can't think of one in the standard library, but implementations probably exist out there - then again it'd be pretty easy to write your own.

这篇关于ZipInputStream不报告读取的“实际"(即压缩)字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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