MediaStore
不会覆盖文件,而是创建一个同名的新文件并在其中附加一个数字
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()
}
}
}
如果我调用exportToFile("test.txt", "Hello world")
,它会写入一个文件test.txt。如果我再次调用相同的函数,它会在同一文件夹中创建一个名为 test(1).txt 的新函数。我如何覆盖它并使其写入同一个文件?
answer 并进行了一些修改,这是我的 Kotlin 解决方案
fun exportToFile(fileName: String, content: String) {
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")
// query for the file
val cursor: Cursor? = context.contentResolver.query(
extVolumeUri,
null,
MediaStore.MediaColumns.DISPLAY_NAME + " = ? AND " + MediaStore.MediaColumns.MIME_TYPE + " = ?",
arrayOf(fileName, "text/plain"),
null
)
var fileUri: Uri? = null
// if file found
if (cursor != null && cursor.count > 0) {
// get URI
while (cursor.moveToNext()) {
val nameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
if (nameIndex > -1) {
val displayName = cursor.getString(nameIndex)
if (displayName == fileName) {
val idIndex = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
if (idIndex > -1) {
val id = cursor.getLong(idIndex)
fileUri = ContentUris.withAppendedId(extVolumeUri, id)
}
}
}
}
cursor.close()
} else {
// insert new file otherwise
fileUri = context.contentResolver.insert(extVolumeUri, contentValues)
}
if (fileUri != null) {
val os = context.contentResolver.openOutputStream(fileUri, "wt")
if (os != null) {
os.write(content.toByteArray())
os.close()
}
}
}
RELATIVE_PATH
。原来我漏掉了一个尾部斜杠。插入文件时,可以省略尾部斜杠,因为它会自动添加,但在 WHERE 子句中使用时,它不会相等匹配。