[英]Android get all files in directory nullpointerexception
I'm trying to get all files of a specific directory on the SD card. 我正在尝试获取SD卡上特定目录的所有文件。 Therefore I found this function
因此我发现了这个功能
public static List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".mp3")){
inFiles.add(file);
}
}
}
return inFiles;
}
The problem is the following: If the folder is empty, it will throw a NullPointerException. 问题如下:如果文件夹为空,它将抛出NullPointerException。 How can I avoid this?
如何避免这种情况?
Permissions for read and write on external storage are set. 设置了对外部存储的读取和写入权限。
there is not much to do, if you have to check against null 如果您必须检查是否为null,则没有什么可做的
File[] files = parentDir.listFiles();
if (files == null) {
return inFiles;
}
in your case inFiles
is an empty collection, try to iterating on an empty collection will not case any issues 在您的情况下,
inFiles
是一个空集合,尝试对一个空集合进行迭代不会遇到任何问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.