问题
I was trying to save text file using below code
try {
FileOutputStream fos = new FileOutputStream(TXT_FILE_NAME, true);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write(binding.tvExtractedResult.getText().toString());
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
Toast.makeText(this, "File Saved Successfully", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Error while saving file", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
But the problem is this code doesn't work with Android Q. After this I tried to search the solution and I did this
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues myContentValues = new ContentValues();
myContentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, TXT_FILE_NAME);
String myFolder = "Download/MY_PROJECT";
myContentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, myFolder);
myContentValues.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
myContentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
Uri extVolumeUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
ContentResolver contentResolver = getContentResolver();
Uri uri = contentResolver.insert(extVolumeUri, myContentValues);
if (uri == null) {
Log.e(TAG, "uri is null");
return;
}
Log.e(TAG, "uri=" + uri);
try {
FileOutputStream fos = new FileOutputStream(new File(uri.toString()));
fos.write(binding.tvExtractedResult.getText().toString().getBytes());
fos.close();
} catch (Exception e) {
Log.e(TAG, "error occurred" + e.getMessage());
e.printStackTrace();
} finally {
myContentValues.clear();
myContentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
contentResolver.update(uri, myContentValues, null, null);
}
}
In above code I'm getting uri == null
Appreciate your help. Thanks.
来源:https://stackoverflow.com/questions/61984396/save-txt-file-on-android-q