Java File listFiles(FileFilter filter) method with examples

April 29, 2020 No comments Java IO File Examples listFiles

1. Introduction

The listFiles(FileFilter filter) method returns an array of File objects that represent the files and directories that satisfy specified FileFilter.

2. Method signature

public File[] listFiles(FileFilter filter)

Parameters:

  • FileFilter filter - a file 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. Code snippet that prints only files (!file.isDirectory()) with the .txt extension (file.getName().endsWith(".txt"))

package com.frontbackend.java.io;

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

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File tmp = new File("/tmp/ttt");
            FileFilter fileFilter = file -> !file.isDirectory() && file.getName()
                                                                       .endsWith(".txt");

            File[] list = tmp.listFiles(fileFilter);

            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 the listFiles(FileFilter filter) method that could be used to filter files and directories from the specified path in the filesystem using FileFilter object.

{{ message }}

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