There are several special characters summarized in the following table:
Special Symbols | Meaning |
---|---|
* | Matches zero or more characters of a name component without crossing directory boundaries |
| Matches zero or more characters crossing directory boundaries |
? | Matches exactly one character of a name component |
\ | The escape character used to match the special symbols |
[] | Matches a single character found within the brackets. - matches a range. ! means negation. *, ?, and \ characters match themselves - matches itself if it is the first character within the brackets or the first character after the !. |
{} | Multiple sub patterns. These patterns are grouped together using the curly braces, but are separated within the curly braces by commas. |
The following table presents several examples of useful patterns:
Pattern String | Will Match |
---|---|
*.java | Any filename that ends with .java |
*.{java,class,jar} | Any file that ends with .java, .class, or .jar |
java*[ph].exe | Only those files that start with java and are terminated with either a p.exe or h.exe |
j*r.exe | Those files that start with a j and end with an r.exe |
Instead of using the glob: prefix, we can use regular expressions instead.
To do this, use a reg: prefix followed by a regular expression.
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) { Path directory = Paths.get("C:/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()); }/*from www . ja v a 2s. c o m*/ } } catch (IOException | DirectoryIteratorException ex) { ex.printStackTrace(); } } }