Java examples for File Path IO:Directory Search
java.nio.file.PathMatcher interface provides a method of matching a filename using a glob.
It has a single method matches, which accepts a Path argument.
If the file matches the glob pattern, then it returns true. Otherwise, it returns false.
import java.io.IOException; import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; public class Main { public static void main(String[] args) { // Using the PathMatcher interface to filter a directory Path directory = Paths.get("C:/Program Files/Java/jdk1.7.0/bin"); PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:java?.exe"); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory, "java*.exe")) { for (Path file : directoryStream) { if (pathMatcher.matches(file.getFileName())) { System.out.println(file.getFileName()); }/* w ww . ja va 2s. c o m*/ } } catch (IOException | DirectoryIteratorException ex) { ex.printStackTrace(); } } }