Code:
package c6.s5; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; /** * @author Mikalai Zaikin */ public class PathMatcherExample { public static void main(String... args) throws IOException, InterruptedException { Path startDir = Paths.get("C:\\home"); String pattern = "*.{txt,doc}"; // don't cross directory boundaries ! FileSystem fs = FileSystems.getDefault(); final PathMatcher matcher = fs.getPathMatcher("glob:" + pattern); FileVisitor<Path> matcherVisitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attribs) { Path name = file.getFileName(); if (matcher.matches(name)) { System.out.print(String.format("Found matched file: '%s'.%n", file)); } return FileVisitResult.CONTINUE; } }; Files.walkFileTree(startDir, matcherVisitor); } }
output:
Found matched file: 'C:\home\zaikin\foo\company\readme.txt'. Found matched file: 'C:\home\zaikin\foo\resume.doc'. Found matched file: 'C:\home\zaikin\foo\test.txt'.
![]() ![]() ![]() |