First of all you need to pass through all the files. This is accomplished by using the utility class "Files" and calling the mothod "walkFileTree", that requires as a parameter an object that implements FileVisitor. This interface has methods called each time a file or dir is visited.
Then you need to check for a match and this is accomplished with the interface PathMatcher.
Here's an example:
package org.davis.example; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; class FileSeeker extends SimpleFileVisitor{ private PathMatcher fileMatcher; // Initialize the pattern criteria for the search public FileSeeker(String pattern) { try { fileMatcher = FileSystems.getDefault().getPathMatcher(pattern); } catch (IllegalArgumentException iae) { System.out.println("The pattern is invalid"); System.exit(-1); } } // Pass here every time a file is visited public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) { // Check if the file match if (fileMatcher.matches(path.getFileName())) System.out.println("Match found for: " + path.getFileName()); return FileVisitResult.CONTINUE; } // Pass here every time a dir is visited public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) { System.out.println("Searching in... " + path.toAbsolutePath()); return FileVisitResult.CONTINUE; } } package org.davis.example; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class App { public static void main(String[] args) { // Check parameters if (args.length != 2) { System.out.println("Syntax: ExamineDir "); System.exit(-1); } // Execute the search try { // Set the dir from which to start the search Path src = Paths.get(args[0]); // Walk through all the files and dirs Files.walkFileTree(src, new FileSeeker(args[1])); } catch (IOException e) { System.out.println("An I/O error has occurred!"); } } }
You can use regex or glob pattern.
Here's an example of the parameter passed:
java ExamineDir C:\mydir regex:fil\w+.\w+
or
java ExamineDir C:\mydir glob:fil*.*
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.