我的错误:
for (int i = 0; i <listfiles.length; i ++) {
我不明白,因为如果我已经拥有所有权限。
public static ArrayList<String> getFilePaths(String directory){
ArrayList<String> pathArray = new ArrayList<>();
File file = new File(directory);
File[] listfiles = file.listFiles();
for(int i = 0; i < listfiles.length; i++){
if(listfiles[i].isFile()){
pathArray.add(listfiles[i].getAbsolutePath());
}
}
return pathArray;
}
权限
检查是否已获得许可。
错误:java.lang.NullPointerException:尝试获取空数组的长度
答案 0 :(得分:1)
您需要先请求权限,然后才能像下面这样动态地进行任何操作
if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
}
答案 1 :(得分:0)
从file.Java
关于listFiles()
方法:
* @return An array of abstract pathnames denoting the files and
* directories in the directory denoted by this abstract pathname.
* The array will be empty if the directory is empty. Returns
* {@code null} if this abstract pathname does not denote a
* directory, or if an I/O error occurs.
*
* @throws SecurityException
* If a security manager exists and its {@link
* SecurityManager#checkRead(String)} method denies read access to
* the directory
由于您没有得到SecurityException
并且列表为null
,因此
唯一的其他选择是:
答案 2 :(得分:0)
您应该查看javadoc中的listFiles()方法。
https://developer.android.com/reference/java/io/File.html#listFiles()
如果文件不是目录,则返回null。为了防止空指针,您可以首先使用isDirectory()检查文件对象,如果为false,则不要执行循环。