How do I use directory globbing in JDK7

匆匆过客 提交于 2019-11-30 17:14:49

Here's a working example which displays all the zip files in any descendant directory of d:/:

public static void main(String[] args) throws IOException {
    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:d:/**/*.zip");
    Files.walkFileTree(Paths.get("d:/"), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (matcher.matches(file)) {
                System.out.println(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}

As you see, using forward slashes works on Windows.

You need to start your glob with **

matcher = FileSystems.getDefault().getPathMatcher("glob:**/foo/**/bar/*.dat");

Otherwise, calling

matcher.matches(file)

attempts to match the full path to the file against a regular expression that starts with the relative path (/foo/), rather than with the absolute path (d:/petermr-workspace/.../foo).

Prepending the ** to the glob just tells it to ignore the beginning of the absolute path.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!