且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数据附加到 android 10 (API 29) 中的文本文件

更新时间:2023-01-23 09:36:59

此代码更正(尤其是单词的大写/小写)vaibhav 并使用 blackapps 建议包含文本附加.可以写txt或json.在 Android 10+ 上无需用户交互即可在持久文件夹(例如/storage/self/Downloads)中写入文本(实际上未在 11 上测试,但应该可以工作).

This code corrects (especially words' upper/lower cases) vaibhav ones and use blackapps suggestion to include text append. Can write txt or json. Good to write text in persistent folders (e.g. /storage/self/Downloads) without user interaction on Android 10+ (actually not tested on 11, but should work).

    // filename can be a String for a new file, or an Uri to append it
    fun saveTextQ(ctx: Context,
                  relpathOrUri: Any,
                  text: String,
                  dir: String = Environment.DIRECTORY_DOWNLOADS):Uri?{
    
        val fileUri = when (relpathOrUri) {
            is String -> {
               // create new file
                val mime =  if (relpathOrUri.endsWith("json")) "application/json"
                            else "text/plain"
    
                val values = ContentValues()
                values.put(MediaStore.MediaColumns.DISPLAY_NAME, relpathOrUri)
                values.put(MediaStore.MediaColumns.MIME_TYPE, mime) //file extension, will automatically add to file
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, dir)
                ctx.contentResolver.insert(MediaStore.Files.getContentUri("external"), values) ?: return null
            }
            is Uri -> relpathOrUri   // use given Uri to append existing file
            else -> return null
        }
    
        val outputStream    = ctx.contentResolver.openOutputStream(fileUri, "wa") ?: return null
    
        outputStream.write(text.toByteArray(charset("UTF-8")))
        outputStream.close()
    
        return fileUri  // return Uri to then allow append
    }