Mithun Wijethunga
Mithun Wijethunga

Reputation: 79

FileNotFound Exception when saving an image to sub directory in external storage

private fun takeScreenshot() {
    val now = Date()
    val formattedTimestamp = DateFormat.format("yyyy-MM-dd_hh:mm:ss", now)
    try {
        //val mPath : String = Environment.getExternalStorageDirectory().toString().toString().toString() + "/" + formattedTimestamp + ".jpg"
        // image naming and path  to include sd card  appending name you choose for file
        val mPath: String = Environment.getExternalStorageDirectory().toString().toString() + "/mobile/" + GetSetContext.getApplicationName() + "/Screenshots/" + formattedTimestamp + ".jpg"
            // create bitmap screen capture

        val v = this.view!!

        v.setDrawingCacheEnabled(true)
        v.buildDrawingCache(true)
        val bitmap: Bitmap = Bitmap.createBitmap(v.getDrawingCache())
        v.setDrawingCacheEnabled(false)
        val imageFile = File(mPath)
        val outputStream = FileOutputStream(imageFile)
        val quality = 100
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
        outputStream.flush()
        outputStream.close()
        ScreenshotUploadWorkManager().setupUploadingRequest(context, applicationConfiguration,mPath)

   

I am using the file path mPath here. when I using commented out mPath, there is no issue occuring. But when I use the mPath which is not commented out in the code, I am getting a FileNotFound Exception.

java.io.FileNotFoundException: /storage/emulated/0/mobile/App/Screenshots/2022-06-20_09:00:18.jpg: open failed: EISDIR (Is a directory)

Created these sub directories using Device File Explorer in Android Studio but issue is still occurring. What am I missing here?

Upvotes: 0

Views: 502

Answers (1)

mohit48
mohit48

Reputation: 812

First create a directory using mkdirs() like this

val dir = File(Environment.getExternalStorageDirectory().toString().toString() + "/mobile/" + GetSetContext.getApplicationName() + "/Screenshots/")
if(!dir.exists()){
    dir.mkdirs()
}

Then create a new file for your image

val imageFile = File(dir, formattedTimestamp + ".jpg")

Then copy the stream to image File

Upvotes: 2

Related Questions