First let's create two folders in our working directory and add some text files in them. Then let's rename these files as shown in the figure below.
Since we are done with our files, now we can create our FileFinder class. As you see in the code, this class extends SimpleFileVisitor
FileFinder.java
/**
* Author : Berk Soysal
*/
package herrberk;
import java.io.IOException;
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;
import java.util.ArrayList;
public class FileFinder extends SimpleFileVisitor<Path> {
private PathMatcher matcher;
public ArrayList<Path> foundPaths = new ArrayList<>();
public FileFinder(String pattern) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Path name = file.getFileName();
System.out.println("Examining " + name);
if (matcher.matches(name)) {
foundPaths.add(file);
}
return FileVisitResult.CONTINUE;
}
}
Our main file creates a 'finder' object and visits the file paths in a tree topology until it finds the locations and prints them.
Main.java
/**
* Author : Berk Soysal
*/
package herrberk;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
Path fileDir = Paths.get("files");
FileFinder finder = new FileFinder("file*.txt");
Files.walkFileTree(fileDir, finder);
ArrayList<Path> foundFiles = finder.foundPaths;
if (foundFiles.size() > 0) {
for (Path path : foundFiles) {
System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS));
}
}
else {
System.out.println("No files were found!");
}
}
}
Output
Examining file1.txt
Examining file2.txt
Examining file3.txt
Examining file4.txt
C:\Users\Berk\workspace\FindingFiles\files\dir1\file1.txt
C:\Users\Berk\workspace\FindingFiles\files\dir1\file2.txt
C:\Users\Berk\workspace\FindingFiles\files\dir2\file3.txt
C:\Users\Berk\workspace\FindingFiles\files\dir2\file4.txt
Please leave a comment if you have any questions or comments.
Continue Reading Useful Java Code Snippets 9 - Reading & Writing Byte Streams of an Image
Disqus Comments Loading..