在 Android 12 中,为了保护用户数据,Google 引入了 Scoped Storage 概念,在应用程序外部访问和操作设备的文件变得更加困难。出现“FileNotFound, open failed: EACCES (Permission denied)”错误通常是因为应用试图读取或写入 Scoped Storage 之外的文件。
要解决此问题,最好的方式是使用 Scoped Storage API 来管理和访问文件。例如,使用 getExternalFilesDir() 方法来检索您应用程序的专用目录。以下是一个示例代码片段:
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
File file = new File(getExternalFilesDir(null), "example.txt");
try {
FileWriter writer = new FileWriter(file);
writer.append("This is an example text.");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Permission is not granted
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
}
在此示例中,我们首先检查是否已授予 WRITE_EXTERNAL_STORAGE 权限。如果没有,我们将请求用户授予权限。如果已经有了权限,则我们使用 getExternalFilesDir() 方法检索该应用程序的专用目录,并将文件写入其中。