Find files in a folder using Java
What I need to do if Search a folder say C:\example
I then need to go through each file and check to see if it matches a few start characters so if files start
开发者_如何转开发temp****.txt
tempONE.txt
tempTWO.txt
So if the file starts with temp and has an extension .txt I would like to then put that file name into a File file = new File("C:/example/temp***.txt);
so I can then read in the file, the loop then needs to move onto the next file to check to see if it meets as above.
What you want is File.listFiles(FileNameFilter filter)
.
That will give you a list of the files in the directory you want that match a certain filter.
The code will look similar to:
// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("temp") && name.endsWith("txt");
}
});
You can use a FilenameFilter, like so:
File dir = new File(directory);
File[] matches = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.startsWith("temp") && name.endsWith(".txt");
}
});
I know, this is an old question. But just for the sake of completeness, the lambda version.
File dir = new File(directory);
File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));
Have a look at java.io.File.list()
and FilenameFilter
.
As @Clarke said, you can use java.io.FilenameFilter
to filter the file by specific condition.
As a complementary, I'd like to show how to use java.io.FilenameFilter
to search file in current directory and its subdirectory.
The common methods getTargetFiles and printFiles are used to search files and print them.
public class SearchFiles {
//It's used in dfs
private Map<String, Boolean> map = new HashMap<String, Boolean>();
private File root;
public SearchFiles(File root){
this.root = root;
}
/**
* List eligible files on current path
* @param directory
* The directory to be searched
* @return
* Eligible files
*/
private String[] getTargetFiles(File directory){
if(directory == null){
return null;
}
String[] files = directory.list(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.startsWith("Temp") && name.endsWith(".txt");
}
});
return files;
}
/**
* Print all eligible files
*/
private void printFiles(String[] targets){
for(String target: targets){
System.out.println(target);
}
}
}
I will demo how to use recursive, bfs and dfs to get the job done.
Recursive:
/**
* How many files in the parent directory and its subdirectory <br>
* depends on how many files in each subdirectory and their subdirectory
*/
private void recursive(File path){
printFiles(getTargetFiles(path));
for(File file: path.listFiles()){
if(file.isDirectory()){
recursive(file);
}
}
if(path.isDirectory()){
printFiles(getTargetFiles(path));
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.recursive(searcher.root);
}
Breadth First Search:
/**
* Search the node's neighbors firstly before moving to the next level neighbors
*/
private void bfs(){
if(root == null){
return;
}
Queue<File> queue = new LinkedList<File>();
queue.add(root);
while(!queue.isEmpty()){
File node = queue.remove();
printFiles(getTargetFiles(node));
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs != null){
for(File child: childs){
queue.add(child);
}
}
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.bfs();
}
Depth First Search:
/**
* Search as far as possible along each branch before backtracking
*/
private void dfs(){
if(root == null){
return;
}
Stack<File> stack = new Stack<File>();
stack.push(root);
map.put(root.getAbsolutePath(), true);
while(!stack.isEmpty()){
File node = stack.peek();
File child = getUnvisitedChild(node);
if(child != null){
stack.push(child);
printFiles(getTargetFiles(child));
map.put(child.getAbsolutePath(), true);
}else{
stack.pop();
}
}
}
/**
* Get unvisited node of the node
*
*/
private File getUnvisitedChild(File node){
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs == null){
return null;
}
for(File child: childs){
if(map.containsKey(child.getAbsolutePath()) == false){
map.put(child.getAbsolutePath(), false);
}
if(map.get(child.getAbsolutePath()) == false){
return child;
}
}
return null;
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.dfs();
}
For list out Json files from your given directory.
import java.io.File;
import java.io.FilenameFilter;
public class ListOutFilesInDir {
public static void main(String[] args) throws Exception {
File[] fileList = getFileList("directory path");
for(File file : fileList) {
System.out.println(file.getName());
}
}
private static File[] getFileList(String dirPath) {
File dir = new File(dirPath);
File[] fileList = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
});
return fileList;
}
}
Appache commons IO various
FilenameUtils.wildcardMatch
See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.
Consider Apache Commons IO, it has a class called FileUtils that has a listFiles
method that might be very useful in your case.
To elaborate on this response, Apache IO Utils might save you some time. Consider the following example that will recursively search for a file of a given name:
File file = FileUtils.listFiles(new File("the/desired/root/path"),
new NameFileFilter("filename.ext"),
FileFilterUtils.trueFileFilter()
).iterator().next();
See:
- org.apache.commons.io.FileUtils
- org.apache.commons.io.filefilter.FileFilterUtils
- https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/filefilter/IOFileFilter.html
As of Java 1.8, you can use Files.list to get a stream:
Path findFile(Path targetDir, String fileName) throws IOException {
return Files.list(targetDir).filter( (p) -> {
if (Files.isRegularFile(p)) {
return p.getFileName().toString().equals(fileName);
} else {
return false;
}
}).findFirst().orElse(null);
}
From Java 8 you can use Files.find
Path dir = Paths.get("path/to/search");
String prefix = "prefix";
Files.find(dir, 3, (path, attributes) -> path.getFileName().toString().startsWith(prefix))
.forEach(path -> log.info("Path = " + path.toString()));
You give the name of your file, the path of the directory to search, and let it make the job.
private static String getPath(String drl, String whereIAm) {
File dir = new File(whereIAm); //StaticMethods.currentPath() + "\\src\\main\\resources\\" +
for(File e : dir.listFiles()) {
if(e.isFile() && e.getName().equals(drl)) {return e.getPath();}
if(e.isDirectory()) {
String idiot = getPath(drl, e.getPath());
if(idiot != null) {return idiot;}
}
}
return null;
}
- Matcher.find and Files.walk methods could be an option to search files in more flexible way
- String.format combines regular expressions to create search restrictions
- Files.isRegularFile checks if a path is't directory, symbolic link, etc.
Usage:
//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
stream().forEach(System.out::println);
Source:
public final class PathUtils {
private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
private static final String endsWithRegex = "(?=[\\.\\n])";
private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";
public static List<Path> searchRegularFilesStartsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
}
public static List<Path> searchRegularFilesEndsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
}
public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
return searchRegularFiles(initialPath, "", "");
}
public static List<Path> searchRegularFiles(final Path initialPath,
final String fileName, final String fileExt)
throws IOException {
final String regex = String.format(containsRegex, fileName, fileExt);
final Pattern pattern = Pattern.compile(regex);
try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
return walk.filter(path -> Files.isRegularFile(path) &&
pattern.matcher(path.toString()).find())
.collect(Collectors.toList());
}
}
private PathUtils() {
}
}
Try startsWith regex for \txt\temp\tempZERO0.txt:
(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Try endsWith regex for \txt\temp\ZERO0temp.txt:
temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:
temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
精彩评论