首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在目录中找到一堆文件

在目录中找到一堆文件
EN

Stack Overflow用户
提问于 2014-05-21 14:32:39
回答 1查看 17关注 0票数 0

嗨,我有一个目录,其中包含名字如下的子目录

代码语言:javascript
运行
复制
1-1,
2-3,
4-10,
11-20

现在我想找到范围内的所有目录,比如1-10,所以应该返回dirs 1-1,2-3和4-10。我有下面的代码,但它不像预期的那样工作。

代码语言:javascript
运行
复制
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组合.我该如何解决这个问题?请帮帮忙。提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-21 14:57:32

由于您希望在数字条件上匹配,所以将名称作为字符串进行检查并不是正确的方法。正如@Perneel上面所说的,您要做的是解析目录名以获取它包含的范围并检查这些目录名。

代码语言:javascript
运行
复制
    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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23786286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档