Java File listFiles(FilenameFilter filter) method with examples

April 29, 2020 No comments Java IO FIle Examples listFiles

1. Introduction

The listFiles(FilenameFilter filter) method returns an array of File objects that represent the files and directories that satisfy the specified filter. In case the given filter is null then all pathnames are accepted.

2. Method signature

public File[] listFiles(FilenameFilter filter)

Parameters:

  • FilenameFilter filter - a filename filter

Returns

  • File[] - an array of File objects that represent files and directories that satisfy the specified filter.

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Sample Java snippet that prints only files (!file.isDirectory()) with the .txt extension (s.endsWith(".txt"))

package com.frontbackend.java.io;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File tmp = new File("/tmp/ttt");
            FilenameFilter filenameFilter = (file, s) -> s.endsWith(".txt") && !file.isDirectory();
            File[] list = tmp.listFiles(filenameFilter);

            if (list != null) {
                Arrays.stream(list)
                      .forEach(file -> {
                          System.out.println(file.getPath() + " " + (file.isDirectory() ? "dir" : "file"));
                      });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

/tmp/ttt/dest.txt file
/tmp/ttt/test.txt file

4. Conclusion

In this article, we presented a method to list files that satisfy the specified filter. The listFiles(FilenameFilter filter) method is similar to list(FilenameFilter filter) but in this case, we have a handler to files no just the name in a string.

{{ message }}

{{ 'Comments are closed.' | trans }}