I am trying to read a zipped file using Kotlin and ZipInputStream into a 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
}
The error I get is:
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>
I thought maybe zis.use
is closing the entry already after the contents of the entry are read, so I removed zis.closeEntry()
, but then it produced the same error when trying to get the next entry
I know zis.use
is safe and guarantees the input stream is closed, but I would expect it to close just the entry if anything rather than the entire stream.
Having printed the entire byte array, I know only the first file in the zip is being read during zis.use
Is there a good way to read all entries in a ZipInputStream in kotlin?
use
. I didn't realize thecopyTo
method can actually be called on any input stream even outside ofuse
– Exclamation