Filtering a directory using globbing - Java File Path IO

Java examples for File Path IO:Directory Search

Introduction

Globbing strings are based on patterns.

Special SymbolsMeaning
* 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. A - matches a range. A ! means negation. The *, ?, and \ characters match themselves, and a - matches itself if it is the first character within the brackets or the first character after the !.
{ }Multiple subpatterns can be specified at the same time. 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 potentially useful globbing patterns:

Globbing 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

Demo Code

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:/Program Files/Java/jdk1.7.0/bin");
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory, "java*.exe")) {
      for (Path file : directoryStream) {
        System.out.println(file.getFileName());
      }/*from  ww  w.  jav  a 2 s  .com*/
    } catch (IOException | DirectoryIteratorException ex) {
      ex.printStackTrace();
    }

  }
}

Related Tutorials