【发布时间】:2019-02-17 05:32:46
【问题描述】:
我正在尝试使用 Kotlin 和 ZipInputStream 将压缩文件读入 ByteArrayOutputStream()
val f = File("/path/to/zip/myFile.zip")
val zis = ZipInputStream(FileInputStream(f))
//loop through all entries in the zipped file
var entry = zis.nextEntry
while(entry != null) {
val baos = ByteArrayOutputStream()
//read the entry into a ByteArrayOutputStream
zis.use{ it.copyTo(baos) }
val bytes = baos.toByteArray()
System.out.println(bytes[0])
zis.closeEntry() //error thrown here on first iteration
entry = zis.nextEntry
}
我得到的错误是:
java.io.IOException: Stream closed
at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:67)
at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:139)
<the code above>
我想也许zis.use 在读取条目的内容后已经关闭了该条目,所以我删除了zis.closeEntry(),但是在尝试获取下一个条目时它产生了同样的错误
我知道zis.use 是安全的并保证输入流已关闭,但我希望它只关闭条目而不是整个流。
打印了整个字节数组后,我知道在zis.use 期间只读取了 zip 中的第一个文件
有没有一种好方法可以读取 kotlin 中 ZipInputStream 中的所有条目?
【问题讨论】:
标签: java kotlin zipinputstream