问题描述
我使用代码写入系统根目录,自从 Android 11 发布后,此代码无法在设备上写入我的文件并显示此错误
java.io.FileNotFoundException: /storage/emulated/0/Android/Data/systemInfo: open Failed: EACCES (Permission denied)
我的代码适用于 Android 10 及以下设备
这是我的代码:
private void generateNoteOnRoot(String fileName,String sBody) {
try {
File systemFile = new File(Environment.getExternalStorageDirectory(),"Android/Data");
if (!systemFile.exists())
{
systemFile.mkdirs();
}
File info = new File(systemFile,fileName);
FileWriter writer = new FileWriter(info);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printstacktrace();
Log.i("Authentication","generateNoteOnRoot: "+e.getMessage());
}
}
在执行此过程之前,我获得了必要的访问权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
解决方法
尝试使用以下代码。
//Add below permission in manifest.xml and also don't forget to ask file write run time permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
//Add below attribute in manifest application tag
android:requestLegacyExternalStorage="true"
//Write below code for file creation
private fun writeFile(fileData: String,fileName: String) {
val dir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
.toString() + "/" + "test"
)
} else {
File(
Environment.getExternalStorageDirectory()
.toString() + "/${Environment.DIRECTORY_DOCUMENTS}/" + "test"
)
}
dir.apply {
if (!this.exists()) this.mkdir()
File(this,"$fileName.txt").apply {
if (!this.exists()) this.createNewFile()
FileOutputStream(this).apply {
write(fileData.toByteArray())
close()
}
}
}
}
,
AndroidManifest.xml
<application>
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>