如何在Android 10以上版本中使用MediaStore编辑文件而不是创建新文件? [英] How to edit a file instead of creating a new one using MediaStore above Android 10?
问题描述
我尝试使用带有以上代码的MediaStore在文档"外部目录中创建文件:
I've tried to create a file in Documents external directory using MediaStore with the above code :
val resolver = applicationContext.contentResolver
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "doc.txt")
put(MediaStore.MediaColumns.MIME_TYPE, "text/plain")
put(MediaStore.MediaColumns.RELATIVE_PATH, "Documents")
}
val uri = resolver.insert(MediaStore.Files.getContentUri("external"), contentValues)
uri?.let {
resolver.openOutputStream(it).use {
// Write file
it?.write("line1".toByteArray(Charset.defaultCharset()))
it?.write("line2".toByteArray(Charset.defaultCharset()))
it?.close()
}
}
我第一次执行此代码时,将按预期方式创建文件'doc.txt'.
The first time I execute this code, the file 'doc.txt' is created like expected.
但是,如果我再次执行相同的代码,它将为我创建一个新文件'doc(1).txt',而不是编辑我已经创建的文件.
But if I execute the same code again, it create me a new file 'doc (1).txt' instead of editing the file I already created.
当原始的'doc.txt'文件已经存在时,该如何修改?
How can I modify the original 'doc.txt' file when it already exist ?
据我了解,因为创建了该文件,所以我应该能够在该文件上写东西.
In my understanding, I should be able to write on this file because I created it.
推荐答案
但是,如果我再次执行相同的代码,它将为我创建一个新文件'doc(1).txt',而不是编辑我已经创建的文件.
But if I execute the same code again, it create me a new file 'doc (1).txt' instead of editing the file I already created.
您的代码有两件事:
- 将新条目插入
MediaStore
- 为
insert()
返回的Uri
打开OutputStream
并将内容写入该流
- Inserts a new entry into the
MediaStore
- Opens an
OutputStream
for theUri
returned byinsert()
and writes content to that stream
如果您不想添加新条目,请不要插入新条目.
If you do not not want a new entry, do not insert one.
当原始的"doc.txt"文件已经存在时,如何修改?
How can I modify the original 'doc.txt' file when it already exist ?
为最初获得的Uri
打开一个OutputStream
,然后将内容写入该流.
Open an OutputStream
for the Uri
that you were given originally, and write content to that stream.
这篇关于如何在Android 10以上版本中使用MediaStore编辑文件而不是创建新文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!