how to search for a file with re in a directory?
I want to search for a file inside a directory. The filename contain some string such as 00012345, while 开发者_StackOverflowthe complete name should be XXXXXX_00012345_XXXXXX.PDF.
Do I need to loop through the directory for the filename of all the files to compare their name? My directory has A LOT of file, I don't want to do it this way.
Plus: The directory contain millions of file, all of them are pdf. I only need one at each time.
You can delegate this job to the java.io.File
class, it has some convenience methods to return lists of files from directories, that match some criteria.
In your case, I'd implement a FilenameFilter
, that tests, if a filename matches you criteria and use this method:
File[] files = directory.listFiles(new FileNameFilter() {
@Override
public boolean accept(File dir, String name) {
return nameMatchesCriteria(); // to be implemented...
}
});
with directory
as an File
object.
There are various convenience methods / libraries to help you do this, as described in other answers. However at some level they all entail reading all of the directory entries, and comparing the names with your pattern.
Why?
Because that is the API that a typical operating system provides for doing this kind of thing. If you have millions of filenames to check, this will inevitably be slow.
If you want to do this kind of thing quickly, you will need to redesign your system so that you have some (directory) structure to the filespace so that you can navigate to the file you need rather than searching. I don't know if this would be feasible for your application.
Implement a java.io.FilenameFilter
the checks for the correct extension (String.endsWith()
) and the presence of the other target string (String.indexOf()
) then pass that to File.listFiles(FilenameFilter)
. The File
in this case, pointing to the directory of interest.
If you require a recursive search, the Apache Commons-IO FileUtils does a great job with listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
FileUtils of commons.io provide direct API for recursive search..
FileUtils.listFiles(, , );
eg.
String extensions = {"pdf", "xml"};
bool recursiveSearch = true;
File dir = new File("<path of directory to be searched>");
Collection searchResult = FileUtils.listFiles(dir , extensions, recursiveSearch );
searchResult will contains all the collections of files recursively searched from the given dir to its recursive depth.
精彩评论