Use PathMatcher to filter a directory in Java

Description

The following code shows how to use PathMatcher to filter a directory.

Example


//  www .  j  a va  2s . co m
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:/Program Files/");
    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());
        }
      }
    } catch (IOException | DirectoryIteratorException ex) {
      ex.printStackTrace();
    }

  }
}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip