如何在Android 10以上版本中使用MediaStore编辑文件而不是创建新文件? [英] How to edit a file instead of creating a new one using MediaStore above Android 10?

查看:907
本文介绍了如何在Android 10以上版本中使用MediaStore编辑文件而不是创建新文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用带有以上代码的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 the Uri returned by insert() 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆