Java - File Input Output Match Paths

Introduction

Java can perform pattern matching on Path objects using the glob and regex patterns.

PathMatcher functional interface performs the match.

It contains a method matches(Path path) method that returns true if the specified path matches the pattern.

The pattern string consists of two parts, syntax and pattern, separated by a colon:

syntax:pattern

The value for syntax is either glob or regex.

The pattern part follows the syntax that depends on the value of the syntax part.

The glob pattern uses the following syntax rules:

Pattern
Rule
*
matches zero or more characters without crossing directory boundaries.
**
match zero or more characters crossing directory boundaries.
?
matches exactly one character.
\
escape the special meaning of the following character. For example, \\ matches a single backslash, and \* matches an asterisk.
[]



a bracket expression, which matches a single character. For example, [aeiou] matches a, e, i, o, or u.
A dash between two characters specifies a range. For example, [a-z] matches all alphabets between a and z.
The exclamation mark ( !) after the left bracket is treated as negation.
For example, [!tyu] matches all characters except t, y, and u.
{}

group of subpatterns by specifying comma-separated subpatterns inside braces ().
For example, {txt, java, doc} matches txt, java, and doc.

The matching of the root component of a path is implementation-dependent.

The following code uses a PathMatcher object to match a path against a glob pattern.

Demo

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    String globPattern = "glob:**txt";
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher(globPattern);
    Path path = Paths.get("C:\\myData\\Main.java");
    boolean matched = matcher.matches(path);
    System.out.format("%s matches %s: %b%n", globPattern, path, matched);
  }// ww w .  j a v  a  2s  .  c  o m
}

Result