“许可被拒绝”写入 context.getFilesDir() 时

发布于 2025-01-04 22:50:10 字数 606 浏览 2 评论 0原文

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

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

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

这在 99.9% 的情况下有效。但我看到一小部分异常,表明我没有创建此文件的权限。例如:

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

为什么会发生这种情况?我可以解决这个问题吗?立即崩溃对于应用程序来说是一次不愉快的初次体验。

The first time a user opens my app, I write a little bit of data to a local file.

I understand that my app needs permission to write to this file, so I'm using getFilesDir() like so:

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

This works in 99.9% of cases. But I see a small trickle of exceptions saying that I don't have permission to create this file. For example:

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

Why does this happen? Can I work around it? An immediate crash is such an unpleasant first experience with an app.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧夏天 2025-01-11 22:50:10

在 android 清单中授予权限,

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

确保您提供正确的带有扩展名的文件路径,因为您正在获得

java.io.FileNotFoundException

Give permission in android manifest

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

make sure your giving correct path of file with extension as you are getting

java.io.FileNotFoundException
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文