我正在尝试在Nougat模拟器的外部存储目录中创建文件。使用以下代码:

    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test987689");
    if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
    }try {
        if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
            file.createNewFile();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }


许可证:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


我收到以下错误:

W/System.err: java.io.IOException: Permission denied
W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err:     at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
W/System.err:     at java.io.File.createNewFile(File.java:958)
W/System.err:     at com.vibhinna.sreni.SplashActivity.onCreate(SplashActivity.java:41)
W/System.err:     at android.app.Activity.performCreate(Activity.java:6658)
W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2584)
W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2692)
W/System.err:     at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1445)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:154)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6044)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)


我究竟做错了什么?

最佳答案

如果您的targetSdk为23或更高,则应动态请求权限。

了解更多:Requesting Permissions at Run Time

10-06 15:41