我正在尝试在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();
}
PERMISSONS:
<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)
我做错了什么?
答案 0 :(得分:4)
如果您的targetSdk为23或更高,则应动态请求权限。
答案 1 :(得分:2)
获取文件路径,你可以使用 Context.getExternalFilesDir()/ Context.getExternalCacheDir()
例如
unique_ptr
如果文件路径是&#34; Android / data / app package / file name&#34;
,则不需要权限