Android StudioKotlin文件读取

tv6aics1  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(145)

嘿,我有一个工作的FileWrite例程,我可以简单地用

writeFile("Filename as String","Filetext as String")

但是我无法读回文件我尝试了很多解决方案。我只想调用读取例程,如下所示:readFile(“Filename as String”)和文件数据应转到Sting:“从文件发送”

`fun writeFile(name : String, data : String) {
    val contentValues = ContentValues().apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        put(MediaStore.MediaColumns.MIME_TYPE, "text/plain")
        put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + "/Sunny/")
    }

    val extVolumeUri: Uri = MediaStore.Files.getContentUri("external")

    // query for the file
    val cursor: Cursor? = contentResolver.query(
        extVolumeUri,
        null,
        MediaStore.MediaColumns.DISPLAY_NAME + " = ? AND " + MediaStore.MediaColumns.MIME_TYPE + " = ?",
        arrayOf(name, "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 == name) {
                    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 = contentResolver.insert(extVolumeUri, contentValues)
    }

    if (fileUri != null) {
        val os = contentResolver.openOutputStream(fileUri, "wt")

        if (os != null) {
            os.write(data.toByteArray())
            os.close()
        }
    }
}`

我尝试了许多读取例程,但找不到任何可以像写入例程那样调用的例程

km0tfn4u

km0tfn4u1#

我尝试了这个方法,但是它返回“java.io.FileNotFoundException:打开失败:ENOENT(无此类文件或目录)”

fun readFile(name : String) {
    val contentValues = ContentValues().apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        put(MediaStore.MediaColumns.MIME_TYPE, "text/plain")
        put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + "/Sunny/")
    }

    val extVolumeUri: Uri = MediaStore.Files.getContentUri("external")

    var fileUri: Uri? = null

    fileUri = contentResolver.insert(extVolumeUri, contentValues)

    val os = fileUri?.let { contentResolver.openInputStream(it) }

    if (os != null) {
        txtfromfile = os.read().toString()
        os.close()
    }

}

相关问题