在Android API 30及以上版本中,应使用MediaStore API来处理读写外部文件。以下是使用MediaStore API进行读写的示例代码:
读取外部存储器上的文件:
//读取文件的Uri
Uri fileUri = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL);
//需要读取的文件的名称
String fileName = "example.txt";
//构建查询相关的选择和参数
String selection = MediaStore.Downloads.DISPLAY_NAME + "=?";
String[] selectionArgs = new String[] { fileName };
//进行查询,获取文件的Uri
Cursor cursor = getContentResolver().query(fileUri, null, selection, selectionArgs, null);
if(cursor != null && cursor.moveToFirst()) {
int fileIndex = cursor.getColumnIndex(MediaStore.Downloads._ID);
Long fileId = cursor.getLong(fileIndex);
Uri uri = ContentUris.withAppendedId(fileUri, fileId);
//使用getContentResolver()和uri打开文件流
InputStream fileStream = getContentResolver().openInputStream(uri);
}
写入外部存储器上的文件:
//需要写入的文件的Uri
Uri fileUri = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL);
//需要写入的文件的名称
String fileName = "example.txt";
//构建插入操作的ContentValues对象
ContentValues values = new ContentValues();
values.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
values.put(MediaStore.Downloads.MIME_TYPE, "text/plain");
//调用getContentResolver()和insert()方法插入新文件,并返回新文件的Uri
Uri insertUri = getContentResolver().insert(fileUri, values);
//使用getContentResolver()方法打开文件流
OutputStream fileStream = getContentResolver().openOutputStream(insertUri);