简体   繁体   English

Kotlin 如何正确使用 Android 意图保存文件

[英]Kotlin how to properly use Android Intent to save file

I am currently trying to save a text file inside a fragment, but I can't get it to work:我目前正在尝试将文本文件保存在片段中,但无法正常工作:

Here is the method called when the user clicks the save button这是用户单击保存按钮时调用的方法

    private fun saveText(){
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"
        putExtra(Intent.EXTRA_TITLE, "text.txt")
    }
    startActivityForResult(intent, 1)
    }

Here is the onActivityResult method:这是 onActivityResult 方法:

    override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
    if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
        try {
            val path = resultData?.data?.path
            Log.wtf("Path", filePath)
            val writer: Writer = BufferedWriter(FileWriter(path))
            writer.write("Example Text")
            writer.close()
        } catch (e: Exception){
            e.printStackTrace()
        }
    }
}

I also have the permissions set in the manifest and the file itself is created, but nothing is written.我还在清单中设置了权限,并创建了文件本身,但没有写入任何内容。 Perhaps I'm writing to the file wrong?也许我写错了文件?

The error thrown is FileNotFoundException, because its trying to use a file from /document when I'm selecting one from /downloads抛出的错误是 FileNotFoundException,因为当我从 /downloads 中选择一个文件时,它试图使用 /document 中的文件

Suggested solution which unfortunately doesn't work:不幸的是,建议的解决方案不起作用:

                resultData?.data?.let {
                requireActivity().contentResolver.openOutputStream(it).use { stream ->
                    stream!!.bufferedWriter().write("Example Text")
                }
            }

A Uri is not a file. Uri不是文件。

Replace:代替:

        val path = resultData?.data?.path
        Log.wtf("Path", filePath)
        val writer: Writer = BufferedWriter(FileWriter(path))
        writer.write("Example Text")
        writer.close()

with:和:

resultData?.data?.let { contentResolver.openOutputStream(it).use { stream ->
    stream.writer().write("Example Text")
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM