Glob mode in Java NIO
Glob mode in Java NIO
1. What is Glob?
In programming, Glob is a pattern that uses wildcards to specify file names. For example, *. java is a simple Glob, which specifies all files with the extension "java. In Glob mode, two wildcard characters "*" and "?" are widely used. The asterisk represents "any character or character to form a string", while the question mark represents "any single character ".
Glob mode originated from Unix operating systems. Unix provides a "global command", which can be abbreviated as glob. The Glob mode is similar to a regular expression, but it has limited functions.
Ii. Glob mode in Java NIO
The Glob mode is introduced in the NIO library of Java SE7, which is used in the FileSystem class and used in the PathMatcher getPathMatcher (String syntaxAndPattern) method. Glob can be passed as a parameter to PathMatcher. Similarly, you can use Glob to traverse the entire directory in the Files class.
The Glob mode used in Java NIO is as follows:
Iii. Glob example in Java NIO
The following is a Java program that uses the Glob mode to search for a specified directory and Its subdirectories.
- package com.javapapers.java.nio;
- import java.io.IOException;
- import java.nio.file.FileSystems;
- import java.nio.file.FileVisitResult;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.PathMatcher;
- import java.nio.file.Paths;
- import java.nio.file.SimpleFileVisitor;
- import java.nio.file.attribute.BasicFileAttributes;
- public class FileGlobNIO {
- public static void main(String args[]) throws IOException {
- String glob = "glob:**/*.zip";
- String path = "D:/";
- match(glob, path);
- }
- public static void match(String glob, String location) throws IOException {
- final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(
- glob);
- Files.walkFileTree(Paths.get(location), new SimpleFileVisitor
() {
- @Override
- public FileVisitResult visitFile(Path path,
- BasicFileAttributes attrs) throws IOException {
- if (pathMatcher.matches(path)) {
- System.out.println(path);
- }
- return FileVisitResult.CONTINUE;
- }
- @Override
- public FileVisitResult visitFileFailed(Path file, IOException exc)
- throws IOException {
- return FileVisitResult.CONTINUE;
- }
- });
- }
- }
The program output is as follows:
- D:\AndroidLocation.zip
- D:\Eclipse\7dec2014\eclipse-jee-kepler-R-win32-x86_64\workspace\.metadata\.mylyn\.tasks.xml.zip
- D:\Eclipse\7dec2014\eclipse-jee-kepler-R-win32-x86_64\workspace\.metadata\.mylyn\repositories.xml.zip
- D:\Eclipse\7dec2014\eclipse-jee-kepler-R-win32-x86_64\workspace\.metadata\.mylyn\tasks.xml.zip
- D:\mysql-workbench-community-6.2.5-winx64-noinstall.zip
- D:\workspace\Android\AndroidChatBubbles-master.zip
- D:\workspace\Android\Google Chat\XMPPChatDemo.zip
- D:\workspace\Android\Update-Android-UI-from-a-Service-master.zip
- D:\workspace\Android Chat\AndroidDialog.zip
- D:\workspace\Android Wear\AndroidWearPreview.zip