我有一个问题,我知道如何检查文件夹是否为空,但是当我在循环中检查文件夹是否为空时,我总是得到一个错误,这里是我的代码示例,它不起作用。
String sdcard = Environment.getExternalStorageDirectory().toString();
File file = new File(sdcard);
File subFiles[] = file.listFiles();
for(int i=0; i<subFiles.length; i++) {
File subFile = new File(sdcard +"/"+ subFiles[i].getName());
if(subFile.isDirectory() && subFile.listFiles().length==0) {
}
}
我的条件总是出错。
最佳答案
这是您的代码的更好版本,它也是递归代码,意味着它将搜索存储中的所有空文件夹。实际上,空检查不是在这里做的正确的事情,导致 documentation告诉 null
只有当 file
不是目录时才会返回。
public static void traverseEmptyFolders(File root) {
if (root.isFile()) {
throw new IllegalArgumentException("Argument should be a directory.");
}
for (File file : root.listFiles()) {
if (file.isDirectory()) {
File[] contents = file.listFiles();
if (contents == null || contents.length == 0) {
// do something for an empty folder
} else {
traverseEmptyFolders(file);
}
}
}
}
public static void someOtherMethod() {
traverseEmptyFolders(Environment.getExternalStorageDirectory());
}
让我知道这是否有效。
关于android - 如何检查文件夹是否循环为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071338/