其实是没有办法重置ZipInputStream
如您所愿,因为它不支持复位/标记等 但你可以使用ByteArrayOutputStream
缓冲自己InputStream
作为byte[]
所以你写一个类看起来像
private byte[] readStreamBuffer;
private InputStream readStream;
public ZipClass(InputStream readStream){
this.readStream = readStream;
}
和openReadStream
- 方法是这样的:
private ZipInputStream openReadStream(){
if (readStreamBuffer == null) {
//If there was no buffered data yet it will do some new
ByteArrayOutputStream readStreamBufferStream = new ByteArrayOutputStream();
try {
int read = 0;
byte[] buff = new byte[1024];
while ((read = zipFileInput.read(buff)) != -1) {
readStreamBufferStream.write(buff, 0, read);
}
readStreamBuffer = readStreamBufferStream.toByteArray();
}
finally {
readStreamBufferStream.flush();
readStreamBufferStream.close();
}
}
//Read from you new buffered stream data
readStream = new ByteArrayInputStream(readStreamBuffer);
//open new ZipInputStream
return new ZipInputStream(readStream);
}
现在你可以阅读条目,之后将其关闭。如果你打电话openReadStream
它会为您提供一个新的ZipInputStream
,所以你可以选择读取条目是这样的:
public InputStream read(String entry){
ZipInputStream unzipStream = openReadStream();
try {
return readZipEntry(unzipStream, entryName);
}
finally {
unzipStream.close(); //This closes the zipinputstream
}
}
调用方法readZipEntry
private InputStream readZipEntry(ZipInputStream zis, String entry) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// get the zipped file list entry
try {
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
if (!ze.isDirectory() && ze.getName().equals(entry)) {
int len;
byte[] buffer = new byte[BUFFER];
while ((len = zis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
break;
}
ze = zis.getNextEntry();
}
}
finally {
zis.closeEntry();
}
InputStream is = new ByteArrayInputStream(out.toByteArray());
return is;
}
finally {
out.close();
}
}
,你会得到了新的InputStream。您现在可以从同一个输入中多次读取。
'ZipInputStream'是用纯Java编写的一个不同的实现,它不是'ZipFile'的_low-level_。 'ZipFile'使用JNI,不能处理非本地文件。 – 2013-09-22 08:40:43