当前位置: 首页 > 知识库问答 >
问题:

FileNotFoundException:/storage/sdcard0/myfile.txt:open失败:EACCES(拒绝权限)

张绍晖
2023-03-14

在stackoverflow中也有类似的错误,但在尝试解决方案后(如您将在下几行中看到的),我会遇到相同的错误。

我在使用Nexus 5X api 27 oreo rom的模拟器和使用Android4.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>

共有1个答案

谷梁镜
2023-03-14

对于Android>=6.0的设备,您必须在运行时请求权限

对于Android4,适当添加android:maxSDKversion=“18”生成此异常,尝试删除它

编辑:对于Android4.4及以上版本,如果只想写到外部存储,则不WRITE_EXTERNAL_STORAGE,从doc:

 类似资料: