在内部目录中查找一堆文件

时间:2014-05-21 14:32:39

标签: java file io

您好我的目录包含名称如

的子目录
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个组合。我该如何解决这个问题?请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:1)

由于您希望匹配数字标准,因此将名称检查为字符串并不是正确的方法。正如@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
相关问题