问题
I am working on an application where app writes a log file with the currentdate as filename
Ex: 20200710.txt
The earlier was working fine before android 10 but from android 10 the code is no longer writing the file in the external storage.
So I have modified the code a bit for android 10 especially
string logDir = "Documents/MyApp_Data/logs/";
Context context = MyApplication.Context;
ContentValues values = new ContentValues();
values.Put(MediaStore.MediaColumns.DisplayName, filename);
values.Put(MediaStore.MediaColumns.MimeType, "text/plain"); //file extension, will automatically add to file
values.Put(MediaStore.MediaColumns.RelativePath, logDir);
var uri = context.ContentResolver.Insert(MediaStore.Files.GetContentUri("external"), values);
Stream outputStream = context.ContentResolver.OpenOutputStream(uri, "rw");
outputStream.Write(Encoding.UTF8.GetBytes(message));
outputStream.Close();
The above code is working for android 10 but it is creating multiple log files instead I want to update the file if the file already exists. I am not getting a way to check if the file exists then append new data in the existing file. Can someone please let me know? The above code is in Xamarin android but if you have any suggestion that will work in android then I will convert that code to Xamarin android
Thanks in advance
回答1:
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
}
来源:https://stackoverflow.com/questions/64240203/append-data-to-text-file-in-android-10-api-29