0
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?

TiyebM
  • 2,684
  • 3
  • 40
  • 66
  • You can use regexp expressions, and add it to you arrayList if matches. Take a look at [this link](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html) – Santiago Gil Feb 02 '16 at 10:46

2 Answers2

2

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]);
        }
    }
)));
Ferrybig
  • 18,194
  • 6
  • 57
  • 79
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"));
Patrick
  • 831
  • 11
  • 25