Java Files filter directory using glob

Introduction

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].exeOnly 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
import java.io.IOException;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

   public static void main(String[] args) {
      Path directory = Paths.get("C:/bin");
      try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory, "java*.exe")) {
         for (Path file : directoryStream) {
            System.out.println(file.getFileName());
         }/*from  w  w  w.j a  va  2  s.c om*/
      } catch (IOException | DirectoryIteratorException ex) {
         ex.printStackTrace();
      }

   }
}



PreviousNext

Related