Using the Java API
Create an object File
pointing to the directory and itere over the files checks if they have the desired pattern.
Iteration implementation can be done with the method File.listFiles()
, whose parameter is a filter (implementation of FileFilter
) and the return is an array of files (File[]
).
To check the pattern in the file name, you can use a regular expression and the method matches()
class String
.
Take an example:
File pasta = new File(".");
File[] arquivos = pasta.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String nome) {
return nome.matches("\\d+nome.txt");
}
});
for (File file : arquivos) {
System.out.println(file.getName());
}
Using Apache Commons IO
However, if you can use a library like Apache Commons IO, it is possible to simplify using the RegexFileFilter
or the WildcardFileFilter
. See the examples:
File[] arquivos = pasta.listFiles(new RegexFileFilter(""\\d+nome.txt""));
Or:
File[] arquivos = pasta.listFiles(new WildcardFileFilter("*nome.txt"));
Using Google Guava
Another example with Google Guava:
File pasta = new File(".");
Iterable<File> iterable = Files
.fileTreeTraverser()
.breadthFirstTraversal(pasta)
.filter(new Predicate<File>() {
@Override
public boolean apply(File input) {
return input.getName().matches("\\d+nome.txt");
}
});
for (File f : iterable) {
System.out.println(f.getAbsolutePath());
}
Although this is quite verbose, it allows iterating in subdirectories as well.
The class
FileFilter
is from Java, but theRegexFileFilter
is actually from Commons IO.– utluiz
Here in the project I am we prefer to use Commons IO for this facility and others also... we use a lot of Strinutils, Enumutils, Tostringutils... e por ae vai... hehehehe
– Flávio Granato