错误“必须不为空".在科特林 [英] Error "must not be null" in Kotlin

查看:150
本文介绍了错误“必须不为空".在科特林的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.zip文件中有多个文件,我正在尝试获取.尝试解压缩文件会提供java.lang.IllegalStateException:zis.nextEntry不能为null.正确的方法怎么做?

There are multiple files in a .zip file, which I'm trying to get. Trying to unzip the files provides a java.lang.IllegalStateException: zis.nextEntry must not be null. How to do it the right way?

@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,因此您必须进行存储的变量它可以为空:

The ZipEntry you read from the stream will be null when you reach the end of the file, so you have to make the variable that you store it in nullable:

var ze: ZipEntry?

由于它们的平台类型为ZipEntry!,因为它们是Java API,因此您可以将所读取的值分配给一个不可为空的变量-在这种情况下,您必须确定它是否可以为null.请参阅文档有关平台类型的信息更多信息.

You were allowed to assign the values you read to a non-nullable variable because they had the platform type ZipEntry!, since it's a Java API - in this case you have to determine whether it can be null. See the docs about platform types for more information.

这篇关于错误“必须不为空".在科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆