喜欢这个网站!我的问题如下:
我正在读取来自网络的 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/