I have the below code to delete a file I created with FileOutputStream, however it only seems to be deleting the contents of the file, and not the file itself.
I've tried following this to write my code below: Deleting files created with FileOutputStream
What do I need to do to delete the file and not just its contents?
val file = File("myFileName.txt")
try {
val fileOutputStream: FileOutputStream =
context.openFileOutput(
"myFileName.txt",
Context.MODE_PRIVATE
)
fileOutputStream.close()
file.delete()
} catch (e: IOException) {
Log.d(
"Error deleting file",
"${e.localizedMessage}"
)
}
The problem you're having is because you are referring to two different files:
File("myFileName.txt")
is a file in your current working directory.context.openFileOutput("myFileName.txt", Context.MODE_PRIVATE)
is a file associated with this Context's application package.If you're creating the file through the context, you should also delete the file through the context:
context.deleteFile("myFileName.txt")
If, on the other hand, you want to create a file in the current working directory, then you should not use context
but use the Kotlin methods of Path
to write and delete the file. In particular, deleting like this:
path.deleteExisting()
will throw an IOException if it fails to delete, and you can then investigate the cause more easily than the old legacy File.delete method which just returns false and doesn't give a reason.