有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将用于将资产文件复制到Android缓存文件夹的java代码转换为Kotlin的最佳实践

我使用这段代码将Android中的资产文件复制到缓存文件夹,重点是这是一段Java代码,我将其转换为Kotlin,但它看起来更像Java(ish),主要围绕while循环:

val file = File("${cacheDir.path}/$fileName")

val dir = file.parentFile
dir.mkdirs()

val inputStream = assets.open(fileName)

val bufferedOutputStream = BufferedOutputStream(FileOutputStream(file))

val buf = ByteArray(10240)
var num = inputStream.read(buf)
// Java version: while ((num = fi.read(buf)) > 0)
while (num > 0) {
    bufferedOutputStream.write(buf, 0, num)
    num = inputStream.read(buf)
}

bufferedOutputStream.close()
inputStream.close()

任何能让它变得更像Kotlin的专家


共 (3) 个答案

  1. # 1 楼答案

    实际上,完整翻译后,代码应该如下所示:

    val file = File("${cacheDir.path}/$fileName")
    
    val dir = file.parentFile
    dir.mkdirs()
    
    val inputStream = assets.open(fileName).use { input ->
        val bufferedOutputStream = file.outputStream().buffered().use { output ->
            input.copyTo(output, 10240)
        }
    }
    

    这利用了^{}扩展函数、some其他handy 扩展函数和开发人员上面提到的^{}函数,将代码简化为最大值

    PS:Closeable.use应该是Java7 try-with-resource构造的kotlin对应物,具有更好的简单性

  2. # 2 楼答案

    试试科特林的这门课

    /**
    * @fileName: path of file in assets folder
    * For example: getPathFileFromAssets("fonts/text4.ttf") or 
    *getPathFileFromAssets("text4.ttf")
    */
    
    @Throws(IOException::class)
    fun Context.getPathFileFromAssets(fileName: String): String {
    
    var tmpPath = cacheDir.resolve(fileName)
    
    if (tmpPath.exists()) return tmpPath.absolutePath
    
    if (fileName.contains("/")) {
        val folder = fileName.split("/")[0]
        File(cacheDir, folder).also {
            if (it.exists().not()) {
                it.mkdirs()
            }
        }
    }
    tmpPath = File(cacheDir, fileName).also {
        it.outputStream()
            .use { cache ->
                assets.open(fileName)
                    .use { it.copyTo(cache) }
            }
    }
    return tmpPath.absolutePath
    }
    

    在活动中使用

    try {
            val pathFile = getPathFileFromAssets("fonts/text5.ttf")
            val pathFile2 = getPathFileFromAssets("text5.ttf")
        } catch (e: IOException) {
    
        }
    

    注意:必须包括文件文本5。ttf资产文件夹中资产/字体