How to copy file from assets to the app database folder?

I’m new to Kotlin I’m just trying to copy a database file from the assets folder but I keep getting a filenotfound exception. The code is below thanks. I checked double checked the paths. I have another version in java which has no problem.

@Throws(IOException::class)
private fun copyDataBase() {

    val outFileName = DATABASE_PATH + DATABASE_NAME

    val myOutput = FileOutputStream(outFileName)
    val myInput = this.assets.open(DATABASE_NAME)

    val buffer = ByteArray(1024)
    var length: Int = myInput.read(buffer)
    while ((length) > 0) {
        myOutput.write(buffer, 0, length)
        length = myInput.read(buffer)
    }
    myInput.close()
    myOutput.flush()
    myOutput.close()
}

You already asked on Stackoverflow, right?

From this code snippet I can’t say why it doesn’t work.

  • You could show the value of outFileName.
  • You could also show the “equivalent” Java code.
  • You could also show the exact exception message and trace

Note

  • Javadoc of FileOutputStream constructor:
    FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
  • the code is not idiomatic kotlin (nor would it even be clean java code).
1 Like

I don’t really see anything wrong with this code. So if you make a statement such as this, you should at least back it up. (Ok the this. in this.assets.open is not needed but other than that I don’t see anything wrong)

Cleanup should happen in a finally block. Idiomatic kotlin would use the use method. kotlin also provides copyTo method for streams.

Non idiomatic code is not the cause of the exception. Some possibilities are that a path is wrong, the destination folder isn’t created, or the path is to external storage and that permission hasn’t been granted. Hard to tell without more info like a stack trace.

2 Likes