【问题标题】:Cannot read a file from external storage even though permission is granted即使授予权限,也无法从外部存储读取文件
【发布时间】:2018-11-16 10:05:07
【问题描述】:

我正在使用 Android Studio 和虚拟设备(x86 上的 Nexus 5 S)。

出于测试目的,我正在尝试从外部存储读取二进制文件。

当我使用“adb shell”连接到设备时,我可以在 /storage/emulated/0 中找到该文件

在我的测试活动中,我只是把这个:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final String filename = "basse-normandie.map";

    final File file = new File(Environment.getExternalStorageDirectory()
                      .getAbsolutePath(), filename);
    Log.i("FileTests", "file is '"+file.getAbsolutePath()+"'");
    Log.i("FileTests", "file exists: "+file.exists());
    file.setReadable(true);
    Log.i("FileTests", "app can read file: "+file.canRead());

}

在清单中我放了

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

我想 WRITE_EXTERNAL_STORAGE 虽然没用。

在 logcat 窗口中,我得到了这个:

06-25 19:03:46.648 5107-5107/org.airforce_one.filetests I/FileTests: file is '/storage/emulated/0/basse-normandie.map'
    file exists: true
    app can read file: false

我找不到我做错了什么...我在网上查看的每个页面都告诉我授予权限,但没有其他提示...

【问题讨论】:

标签: android android-external-storage


【解决方案1】:

删除final

 File file = new File(Environment.getExternalStorageDirectory()
                  .getAbsolutePath(), filename);

然后改变

file.setReadable(true, false); //the second parameter is specify if the permission is for OwnerOnly

【讨论】:

  • 你需要设置像“file.setReadable(true,false)”这样的可读权限,因为你上面的方法设置了 OwnerOnly 的可读权限。
  • 感谢您的精确度,我不知道。但是,即使进行了此修改,“file.setReadable(true,false)”的值也为 false,因此我的应用程序无权将文件设置为全部可读,以及随后的“file.canRead” ()' 仍然给出 false 作为答案...
【解决方案2】:

我在 .map 文件中遇到了完全相同的问题

file.setReadable(true, false);

解决了。

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2020-01-04
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多