java - ZipInputStream 不报告*实际*(即压缩)字节读取

标签 java inputstream unzip

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

我正在读取来自网络的 HTTP“PUT”请求的 zip 文件。请求 header 告诉我 Content-Length 是(比方说)1Mb。以下代码创建 ZipInputStream,并将 zip 内容保存到当前目录中的文件中:

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 文件。

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

提前致谢!

最佳答案

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 
 */

/**
 * @author clint
 * 
 */
public class ByteCountingInputStream extends FilterInputStream {

  public int totalRead = 0;

  /**
   * @param in
   */
  protected ByteCountingInputStream(InputStream in) {
    super(in);
    // TODO Auto-generated constructor stub
  }

  /* (non-Javadoc)
   * @see java.io.FilterInputStream#read()
   */
  @Override
  public int read() throws IOException {
    int ret = super.read();
    totalRead++;
    return ret;
  }

  /* (non-Javadoc)
   * @see java.io.FilterInputStream#read(byte[], int, int)
   */
  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    int ret = super.read(b, off, len);
    totalRead += ret;
    return ret;
  }

  /* (non-Javadoc)
   * @see java.io.FilterInputStream#read(byte[])
   */
  @Override
  public int read(byte[] b) throws IOException {
    int ret = super.read(b);
    totalRead += ret;
    return ret;
  }

  /* (non-Javadoc)
   * @see java.io.FilterInputStream#skip(long)
   */
  @Override
  public long skip(long n) throws IOException {
    //What to do?
    return super.skip(n);
  }

  /**
   * @return the totalRead
   */
  protected int getTotalRead() {
    return this.totalRead;
  }

}

这介于两者之间

ZipInputStream zis = new ZipInputStream(new ByteCountingInputStream(inputStream));

关于java - ZipInputStream 不报告*实际*(即压缩)字节读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/826390/

相关文章:

java - Play 2 JPA Oracle - 即使 ebeanEnabled 在 build.scala 中设置为 false,也会出现额外列 'ebean_intercept'

java - 解析错误 : Parse#enableLocalDatastore(Context )` must be invoked before ` Parse#initialize(Context)`

java - 下载的文件已损坏,由 Java 中的客户端共享

java - 从 R.raw 文件夹中打开文件

excel - 提取 zip 文件时出现错误 'run-time error -2147024894(80070002)' ...

java - 如何访问JNLP中指定的启动画面?

java - 使用 Quartz 或任何其他 java api 进行动态作业调度

list - 将输入流转换为对象列表

java - 拆分两个文件

java - jdk src 文件无法解压