I want to write to a file periodically and always replace it if already exists. The problem is that, using MediaStore
, instead of overwriting the file, it creates a new one with the same name and appends a number to it
fun exportToFile(fileName: String, content: String) {
// save to downloads folder
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "text/plain")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
val extVolumeUri: Uri = MediaStore.Files.getContentUri("external")
val fileUri = context.contentResolver.insert(extVolumeUri, contentValues)
// save file
if (fileUri != null) {
val os = context.contentResolver.openOutputStream(fileUri, "wt")
if (os != null) {
os.write(content.toByteArray())
os.close()
}
}
}
If I call exportToFile("test.txt", "Hello world")
, it writes a file test.txt. If I call the same function again, it creates a new one called test(1).txt in the same folder. How do I override this and make it write to the same file?