写入 context.getFilesDir() 时“权限被拒绝”

abs*_*ent 5 file-io android permission-denied

用户第一次打开我的应用程序时,我将一些数据写入本地文件。

我知道我的应用程序需要写入这个文件的权限,所以我使用 getFilesDir() 像这样:

File ins = new File(context.getFilesDir(), "INSTALLATION");
// do some things
FileOutputStream out = FileOutputstream.new(ins);
out.write(data.toString().getBytes());
out.close();
Run Code Online (Sandbox Code Playgroud)

这适用于 99.9% 的情况。但是我看到一小部分例外情况,表明我无权创建此文件。例如:

java.lang.RuntimeException: Unable to create application com.blah.blah.Blah
java.lang.RuntimeException: java.io.FileNotFoundException: /INSTALLATION (Permission denied)
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?我可以解决它吗?一个直接的碰撞是这样使用应用程式时不愉快的初次体验。

Tof*_*mad -2

在 android 清单中授予权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

确保您提供正确的带有扩展名的文件路径

java.io.FileNotFoundException
Run Code Online (Sandbox Code Playgroud)

  • 不,那是不对的。您可以写入应用程序的存储,而无需请求用户访问外部存储。正如我所说,99.9% 的情况下写入都会成功;路径和名称始终相同,因此这不是权限问题或路径不正确。 (2认同)