filenotfoundexception – FileOutputStream("dest_path") throws exception in android 9 (pie)-ThrowExceptions

Exception or error:

I have read so many threads on SO and other platforms as well but nothing seems to solve the problem.
This is how I am doing it in kotlin,

val dest = getDestFile()  // method defined bellow
if(dest != null){
    try {
        // dest = full_path/main_dir/nested_dir/another_nested_dir/IMG_123456789.jpg
        val out = FileOutputStream(dest)  **//This line gives crash**
    } catch (e: Exception) {
        inputStream.close()
        e.printStackTrace()
    }
}

fun getDestFile() : File?{
    var file = File(Environment.getExternalStorageDirectory(), "main_dir/nested_dir")
    if (!file.exists()) {
        file.mkdir()
        file = File(file, "another_nested_dir")  //RESULT: full_path/main_dir/nested_dir/another_nested_dir
        if (!file.exists()) {
            file.mkdir()
            file = File(file, "IMG-" + System.currentTimeMillis() + ".jpg") //RESULT: full_path/main_dir/nested_dir/another_nested_dir/IMG-123456789.jpg
            if (file.getParentFile() != null) {
                if (!file.exists()) {
                    file.createNewFile()
                }
            } else {
                file.parentFile.mkdirs()
                if (!file.exists()) {
                    file.createNewFile()
                }
            }
            return file
        }
    }
    return null
}

I have mentioned where the crash is but I am unable to find why is this happening. The application is crashing with a message,

File does not exists

The same code is working perfectly on android 8.1 and bellow. Please share your expertise about this.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *