嗨,我有一个目录,其中包含名字如下的子目录
1-1,
2-3,
4-10,
11-20
现在我想找到范围内的所有目录,比如1-10,所以应该返回dirs 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组合.我该如何解决这个问题?请帮帮忙。提前谢谢。
发布于 2014-05-21 14:57:32
由于您希望在数字条件上匹配,所以将名称作为字符串进行检查并不是正确的方法。正如@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
https://stackoverflow.com/questions/23786286
复制相似问题