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 fil
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"));
Consider Apache Commons IO, it has a class called FileUtils that has a listFiles method that might be very useful in your case.
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");
}
});
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.
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);
}