无法读取 android 上子目录中的文件

Can't read file in subdirectory on android

我正在尝试从我的 Galaxy S4 上的文件夹中读取文件。当我把文件放在根目录时,我可以毫无问题地访问它:

File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "MyFile");

但是我想把我的文件放在一个子目录中。当我创建一个文件夹 'A' 时,将我的文件放入其中并尝试通过以下方式访问它:

File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separatorChar + "A", "MyFile");

我看不懂。当我可以访问 root 时,我是否需要某种许可,其背后的逻辑是什么?

您可以在这里阅读:

http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()

不建议访问此文件夹:

Applications should not directly use this top-level directory, in order to avoid polluting the user's root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled.

此外,需要权限:

Writing to this path requires the WRITE_EXTERNAL_STORAGE permission, and starting in read access requires the READ_EXTERNAL_STORAGE permission, which is automatically granted if you hold the write permission.

[编辑]

此外,由于您使用的是 s4 - 可能是 4.4+ 设备,您应该知道,由于 KitKat Google 不允许对可移动媒体进行写访问,因此您只能读取它,或将其写入您的设备应用程序文件夹:

http://commonsware.com/blog/2014/04/09/storage-situation-removable-storage.html

As a result, apps can read files on removable media using the various undocumented and unsupported tricks for finding removable media. However, apps cannot write to or otherwise modify such removable storage. Note that device manufacturers themselves may have ways of dealing with this, but ordinary app developers do not.