Tiyeb Bellal Tiyeb Bellal - 24 days ago 9
Java Question

How to get a file with exact extension from ArrayList of files

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?

Answer

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.

Single extension filter

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")
)));

Multiple extension filter

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]);
        }
    }
)));