File f = new File("abstract_pathnames");
ArrayList<File> files = new ArrayList<File> (Arrays.asList(f.listFiles()));
How can I get a file with specific extension from this list?
File f = new File("abstract_pathnames");
ArrayList<File> files = new ArrayList<File> (Arrays.asList(f.listFiles()));
How can I get a file with specific extension from this list?
You can use a FilenameFilter
to filter the files. The name of the file is passed a a String, to prevent the creation of large amounts of File
objects when listing the files.
This class exists since JDK 1.0.
Java 7 and lower example:
List<File> files = new ArrayList<File>(Arrays.asList(f.listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".ext");
}
}
)));
Java 8 example:
List<File> files = new ArrayList<File>(Arrays.asList(f.listFiles(
(File dir, String name) -> name.endsWith(".ext")
)));
When filtering multiple extensions, it will become harder. We first store the allowed extensions in a Set<>, then use its contains() method to compare every entry.
Set<String> allowed = new HashSet<>();
allowed.add("txt");
allowed.add("exe");
allowed.add("sh");
Then we split on dot in the file filter and compare the last part:
List<File> files = new ArrayList<File>(Arrays.asList(f.listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String[] split = name.split("\.");
if(split.length == 1)
return allowed.contains("");
return allowed.contains(split[split.length - 1]);
}
}
)));
You can use the following code (Java 8) to get, for example, all the pdf
files of a directory :
File dir = new File("/myDirectory");
File[] files = dir.listFiles(f -> f.getName().endsWith(".pdf"));