嗨,我有一个目录,其中包含名称类似于
的子目录1-1,
2-3,
4-10,
11-20
现在我想找到 1-10 范围内的所有目录,因此它应该返回目录 1-1,2-3 和 4-10。我有以下代码,但它没有按预期工作。
File files[] = folder.listFiles(new FileFilter() {
public boolean accept(File file) {
String name = file.getName().toLowerCase();
if (name.startsWith("1-") || name.endsWith("-10"))
return true;
return false;
}
});
上面的代码给出了输出 1-1 和 4-10,它不包括 2-3 的组合。我该如何解决这个问题?请帮忙。提前致谢。
最佳答案
由于您想要根据数字标准进行匹配,因此将名称作为字符串进行检查并不是正确的方法。正如 @Perneel 上面所说,您要做的是解析目录名称以获取它包含的范围并检查这些范围。
File[] files = folder.listFiles(new FileFilter() {
public boolean accept(File file) {
try {
String[] bounds = file.getName().toLowerCase().split("-");
return (Integer.parseInt(bounds[0]) <= 10 && Integer.parseInt(bounds[1]) >= 1);
} catch (Exception e) {
// array index out of bounds & number format exceptions mean
// this isn't a directory with the proper name format
return false;
}
}
});
System.out.println(Arrays.toString(files)); // 1-1, 2-3, 4-10
关于java - 在内部目录中找到一堆文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786286/