I am trying to create a password-protected zip file using zip4j that contains several files. This is the code I have so far
fun createZipFile(filename: String, vararg containers: Pair<String, ByteArray?>): ByteArray {
val out = ByteArrayOutputStream()
val zipFile = ZipOutputStream(out, passwordGenerator.generate());
try {
for ((name, file) in containers.toList()) {
if (file != null) {
val parameters = createZipParameters(name)
zipFile.putNextEntry(parameters)
zipFile.write(file)
zipFile.closeEntry()
}
}
// return here cause error
return out.toByteArray()
}
finally {
zipFile.close()
out.close()
}
}
I received an "inappropriate format" error when I tried to open the file. However, when I made a small change and moved the return statement after the finally block, it worked fine
// return out.toByteArray()
}
finally {
zipFile.close()
out.close()
}
return out.toByteArray()
Can you explain why this change made a difference and why the original code did not work?