Java - File Input Output File filter

Introduction

To exclude all files from the list with an extension .SYS, use a file filter represented by functional interface FileFilter.

It contains an accept() method that takes the File as an argument and returns true if the File should be listed.

Returning false does not list the file.

The following code creates a file filter that will filter files with the extension .SYS.

// Create a file filter to exclude any .SYS file
FileFilter filter = file -> {
        if (file.isFile()) {
                String fileName = file.getName().toLowerCase();
                if (fileName.endsWith(".sys")) {
                        return false;
                }
        }
        return true;
};

The following code creates two file filters-one filters only files and another only directories:

// Filters only files
FileFilter fileOnlyFilter = File::isFile;

// Filters only directories
FileFilter dirOnlyFilter = File::isDirectory;

The following code shows how to use a file filter.

Demo

import java.io.File;
import java.io.FileFilter;

public class Main {
  public static void main(String[] args) {
    // Change the dirPath value to list files from your directory
    String dirPath = "C:\\";
    File dir = new File(dirPath);
    // Create a file filter to exclude any .SYS file
    FileFilter filter = file -> {
      if (file.isFile()) {
        String fileName = file.getName().toLowerCase();
        if (fileName.endsWith(".sys")) {
          return false;
        }/*from ww  w.  j a  va2  s .c o  m*/
      }
      return true;
    };

    // Pass the filter object to listFiles() method
    // to exclude the .sys files
    File[] list = dir.listFiles(filter);

    for (File f : list) {
      if (f.isFile()) {
        System.out.println(f.getPath() + " (File)");
      } else if (f.isDirectory()) {
        System.out.println(f.getPath() + " (Directory)");
      }
    }
  }
}

Result