Listing files in a directory matching a pattern in Java [duplicate]
See File#listFiles(FilenameFilter).
File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
for (File xmlfile : files) {
System.out.println(xmlfile);
}
Since Java 8 you can use lambdas and achieve shorter code:
File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));
Since java 7 you can the java.nio package to achieve the same result:
Path dir = ...;
List<File> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
for (Path entry: stream) {
files.add(entry.toFile());
}
return files;
} catch (IOException x) {
throw new RuntimeException(String.format("error reading folder %s: %s",
dir,
x.getMessage()),
x);
}
The following code will create a list of files based on the accept method of the FileNameFilter
.
List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".exe"); // or something else
}}));