在Android 11中,应用程序默认无法读写SD卡/Android/someapp目录。若需要访问该目录,需要利用媒体存储库(MediaStore)来进行文件I/O操作。以下是一个简单的代码示例:
private static final String RELATIVE_DIRECTORY = "/someapp/"; // 相对目录名
private static final String MIME_TYPE_TEXT = "text/plain"; // 文件类型
// 获取sdcard/Android/someapp目录
public static File getExternalStorageDirectory(Context context) {
File file;
if (context.getExternalMediaDirs().length > 0) {
// 检查应用程序目录是否存在
file = new File(context.getExternalMediaDirs()[0], RELATIVE_DIRECTORY);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e(TAG, "getExternalStorageDirectory: failed to create directory");
return null;
}
}
} else {
Log.e(TAG, "getExternalStorageDirectory: external media dirs length <= 0");
file = context.getExternalFilesDir(null);
}
return file;
}
// 写入文件内容到sdcard/Android/someapp目录
public static boolean writeFileToExternalStorage(Context context, String fileName, String content){
File file = new File(getExternalStorageDirectory(context), fileName);
try {
FileWriter writer = new FileWriter(file, false);
writer.write(content);
writer.flush();
writer.close();
return true;
} catch (IOException e) {
Log.e(TAG, "writeFileToExternalStorage: failed to write file", e);
return false;
}
}
// 读取文件内容从sdcard/Android/someapp目录
public static String readFileFromExternalStorage(Context context, String fileName){
File file = new File(getExternalStorageDirectory(context), fileName);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
reader.close();
return content.toString