How to get URI from an asset File?

后端 未结 11 1652
慢半拍i
慢半拍i 2020-11-22 14:27

I have been trying to get the URI path for an asset file.

uri = Uri.fromFile(new File(\"//assets/mydemo.txt\"));

When I check if the file

11条回答
  •  被撕碎了的回忆
    2020-11-22 14:56

    Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.

    @Throws(IOException::class)
        fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
                .also {
                   if (!it.exists()) {
                    it.outputStream().use { cache ->
                        context.assets.open(fileName).use { inputStream ->
                                inputStream.copyTo(cache)
                        }
                      }
                    }
                }
    

    Get the path to the file like:

    val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath
    

提交回复
热议问题