In my kotlin Android app, I want to create a new file in the external storage folder. I have the following code:
if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
Log.e("TAG", "${Environment.getExternalStorageState()}")
return
}
var directory: File? = null
var file: File? = null
directory = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "SecretsApp")
try {
directory?.mkdirs()
} catch (e: SecurityException) {
Log.e("TAG", e.toString())
return
}
if (directory != null) {
try {
var filename = "$groupName-privatekey.secretsapp"
Log.i("AttachmentProcessing", filename)
file = File(directory, filename)
var created = file.createNewFile()
} catch(e: Exception) {
Log.e("TAG", e.toString()
return
}
}
My manifest.xml
has <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
too set. However, when I run the above code, I get an Exception at the createNewFile
line as java.io.IOException: No such file or directory
. Any idea why I am not able to create the file ? I am sure there is no file existing by that name there and even if a file exists, I want it to be over-written. How to fix this ?