Listing the Content by Applying a Glob Pattern - Java File Path IO

Java examples for File Path IO:Directory Content

Introduction

Java defines this particular pattern as a built-in glob filter.

A glob pattern is a string pattern which respect some rules, as follows:

  • *: Match any number of characters, including none.
  • **: Similar to *, but cross directories' boundaries.
  • ?: Match exactly one character.
  • {}: Represent a collection of subpatterns separated by commas. For example, {A,B,C} matches A, B, or C.
  • []: Convey a set of single characters or a range of characters if the hyphen character is present.

Some common examples for []:

  • [0-9]: Matches any digit
  • [A-Z]: Matches any uppercase letter
  • [a-z,A-Z]: Matches any uppercase or lowercase letter
  • [12345]: Matches any of 1, 2, 3, 4, or 5

Within the square brackets, *, ?, and \ match themselves.

All other characters match themselves.

To match *, ?, or the other special characters, escape them by using the backslash character, \.

For example, \\ matches a single backslash, and \? matches the question mark.

The following example will extract all files of type PNG, JPG, and BMP.

Demo Code

import java.io.IOException;
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 path = Paths.get("C:/folder1/folder2/folder4");  
  
    //glob pattern applied  
    System.out.println("\nGlob pattern applied:");  
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, "*.{png,jpg,bmp}")) {  
         for (Path file : ds) {  
              System.out.println(file.getFileName());  
         }  //from w  w w .j  a v  a2  s.c o m
    } catch (IOException e) {  
        System.err.println(e);  
    }  
  }
}

Result


Related Tutorials