androidkotlinandroid-assets

File not found while reading json file on Asset folder using kotlin


I am trying to write a new json data on my json file which is located in asset folder inside mcdata folder.

fun writeToFile(fileName: String, fileContent: String) {
        try {
            val fileOutputStream = FileOutputStream(this.resources.assets.openFd("mcdata/$fileName").fileDescriptor)
            val outputWriter = OutputStreamWriter(fileOutputStream)
            outputWriter.write(fileContent)
            outputWriter.close()
        } catch (e: Exception) {
            "Exception: ${e.message}".toLog()
        }
    }

I am getting File not found Exception on

FileOutputStream(this.resources.assets.openFd("mcdata/$fileName").fileDescriptor)

But when I use this.resources.assets.open("mcdata/$fileName") the it return the InputStream without any issue.

How I can write the new jsonObject on the file, which is located in mcdata/$fileName under asset folder


Solution

  • We can't edit/modify data in asset folder in run time or after application installed. assets folder are read only.

    So we move files into Internal Storage or to cacheDir to edit it.