I'm looking for a way to get a list of files that match a pattern (pref regex) in a given directory.
I've found a tutorial online that uses apache's commons-io package with the following code:
Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)
{
File directory = new File(directoryName);
return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null);
}
But that just returns a base collection (According to the docs it's a collection of java.io.File
). Is there a way to do this that returns a type safe generic collection?
Since Java 8 you can use lambdas and achieve shorter code:
See File#listFiles(FilenameFilter).
Since java 7 you can the java.nio package to achieve the same result:
The following code will create a list of files based on the accept method of the
FileNameFilter
.What about a wrapper around your existing code:
I will throw a warning though. If you can live with that warning, then you're done.