OutpuStream gives error ENOTDIR in Android application

63 views Asked by At

I am trying to copy a file that I pick from the gallery to the application's private directory but I cannot move past this point.

First, my code is this

private fun copyImage(context: Context, uri: Uri) {
    val fileName = getFileName(context, uri)
    val appPath = applicationInfo.dataDir

    if (uri.path != null) {
        if (uri.scheme == "content") {
            val imagesFolder = File("$appPath/images")
            if (!imagesFolder.exists()) {
                imagesFolder.mkdirs()
            }

            val inputStream = contentResolver.openInputStream(uri)
            val imageFile = File("$appPath/images/$fileName")

            inputStream.use { input ->
                imageFile.outputStream().use { output ->
                    input!!.copyTo(output)
                }
            }
            inputStream?.close()
        }
    }
}

The file is picked, I get a valid URI but I get an error at this line

imageFile.outputStream().use { output ->

It says something like this

java.io.FileNotFoundException: /data/user/0/com.my.app/images/1000006043.jpg: open failed: ENOTDIR (Not a directory)
at libcore.io.IoBridge.open(IoBridge.java:574)
at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
at com.my.app.AddImageActivity.copyImage(AddImageActivity.kt:99)

I also tried imageFile.createNewFile() but I get a similar error. I added the android.permission.READ_MEDIA_IMAGES permission in the manifest file. I am out of ideas right now

1

There are 1 answers

0
alexmro On

Finally, I found the solution. I had to get the application directory in a different way (though it most likely returns the same path as before)

val appPath = context.filesDir.absolutePath

and then I had to join it with the file name

val imageFile = File(imagesFolder, fileName)