Overview
I’m in the process of porting a simple utility app over from C# into Java and as part of this I’m writing some helper methods for items where I prefer C#’s semantics. Once such case is Directory.GetFiles.
Current Code
import java.io.File;
import java.io.FilenameFilter;
public class Directory {
public static String[] GetFiles(String path) {
File directory = new File(path);
return directory.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return new File(dir, filename).isFile();
}
});
}
}
Question
Whilst the above all seems fine, and replicates one of the GetFiles overloads, I’m stuck on how best to write a method that replicates the functionality of C#’s Directory.GetFiles(String, String).
This method should take a path string, as well as a searchPattern, which is used to return only files matching that particular pattern.
For example, each of the following should work:
// Used to get all JavaScript files
Directory.GetFiles("~/Documents/", "*.js");
// Get all CSS files in the styles sub-folder.
Directory.GetFiles("~/Documents/", "styles/*.css");
You could modify the pattern by placing a period before each asterisk and question mark, and then use this as a regular expression to determine which files you should return. So, you could write something like