我正在尝试获取一个.zip文件中的多个文件.尝试解压缩文件会提供java.lang.IllegalStateException:zis.nextEntry不能为null.如何正确地做呢?
@Throws(IOException::class)
fun unzip(zipFile: File, targetDirectory: File) {
val zis = ZipInputStream(
BufferedInputStream(FileInputStream(zipFile)))
try {
var ze: ZipEntry
var count: Int
val buffer = ByteArray(8192)
ze = zis.nextEntry
while (ze != null) {
val file = File(targetDirectory, ze.name)
val dir = if (ze.isDirectory) file else file.parentFile
if (!dir.isDirectory && !dir.mkdirs())
throw FileNotFoundException("Failed to ensure directory: " + dir.absolutePath)
if (ze.isDirectory)
continue
val fout = FileOutputStream(file)
try {
count = zis.read(buffer)
while (count != -1) {
fout.write(buffer, 0, count)
count = zis.read(buffer)
}
} finally {
fout.close()
zis.closeEntry()
ze = zis.nextEntry
}
}
} finally {
zis.closeEntry()
zis.close()
}
}
解决方法:
当您到达文件末尾时,从流中读取的ZipEntry将为null,因此必须使将其存储在null中的变量可为空:
var ze: ZipEntry?
您可以将读取的值分配给非空变量,因为它们的平台类型为ZipEntry !,因为它是Java API-在这种情况下,您必须确定其是否可以为null.有关更多信息,请参见docs.