无法在Android文档目录中列出或打开文件
因此,我使用手机上的Excel创建了名为theBook.csv
的文件,该文件已保存到手机的Documents
文件夹中。当我尝试列出手机的Documents
文件夹的内容时,我收到一个NullPointerException
,说我试图to get length of null array
。无法在Android文档目录中列出或打开文件
这是我曾尝试:
String path = Environment.getExternalStorageDirectory().toString() + "/Documents";
// I have also tried:
// String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
// and
// String path = Environment.getRootDirectory().getAbsolutePath() + "/Documents";
Log.i("Files", "The path is: " + path);
File f = new File(path);
File file[] = f.listFiles();
try {
Log.i("Files", "Number of files: "+ file.length);
for (int i = 0; i < file.length; i++) {
Log.i("Files", "Found file with name:" + file[i].getName());
}
} catch (NullPointerException e) {
entoast("NPE"); // my toast message method
e.printStackTrace();
}
当我查看日志的path
值/storage/emulated/0/Documents
(无论是哪个三条线我尝试的),而我不能确定对应到Documents
文件夹,其中theBook.csv
位于。如果是这样,为什么不在日志文件中显示theBook.csv
?如果没有,我怎么让我的程序访问手机的实际Documents
文件夹,而不是一个空目录?
当手机通过USB连接进行文件传输时,Documents文件夹可以查看,而且在使用手机内置的文件浏览器时也是可观的。我在手机上运行Android 6.0,但该应用的最低要求SDK是Android 4.1。我的清单文件中也有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
行。
READ_EXTERNAL_STORAGE进入危险类别权限,您应该请求权限运行时间。此功能在Android 6.0中添加。
要检查权限授予或不
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE);
如果应用许可,该方法返回PackageManager.PERMISSION_GRANTED,并且应用程序可以与operation.Other请求允许运行时间进行。
欲了解更多详情,请访问Android的正式文件
Requesting Permissions at Run Time
对于风险的权限https://developer.android.com/guide/topics/security/permissions.html
我一定会在运行时查看请求权限。同时,应用程序是否会有更优化的外部存储目录来查看这不是Documents目录? –
您必须添加'的完整列表'在清单文件中。 –
READ_EXTERNAL_STORAGE属于危险类别权限,您应该请求权限运行时间。此功能已添加到Android 6.0中 – USKMobility