我正在尝试在应用程序外部的文件夹中的外部存储中写入文件。我在清单中添加了 WRITE_EXTERNAL_STORAGE 权限。
stackoverflow 中也有类似的错误,但是在尝试了解决方案之后(正如您将在我的下一行中看到的那样),我遇到了同样的错误。
我在带有 Nexus 5X api 27 oreo rom 的模拟器和带有 Android 4.4 的华为真手机中都试过了
在这两种设备中,我都遇到了同样的错误:
FileNotFoundException: /storage/sdcard0/Myfile.txt: open failed: EACCES (Permission denied)
这是我的代码:
String content = "hello world";
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "MyFile.txt");
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
} catch (IOException e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
显现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-feature
android:name="android.hardware.location"
android:required="false" />
<uses-feature
android:name="android.hardware.location.gps"
android:required="false" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".activities.Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>