Java Reference
In-Depth Information
}
}
}
C:\WINDOWS (Directory)
C:\MSDOS.SYS (File)
C:\CONFIG.SYS (File)
...
Suppose you wanted to exclude all files from the list with an extension .SYS . You can do this by using a file filter
that is represented by an instance of the functional interface FileFilter . It contains an accept() method that takes
the File being listed as an argument and returns true if the File should be listed. Returning false does not list the file.
The following snippet of code creates a file filter that will filter files with the extension .SYS . Note that the code uses
lambda expressions that were introduced in Java 8.
// 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;
};
Using lambda expressions makes it easy to build the file filters. The following snippet of 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;
Listing 7-5 illustrates how to use a file filter. The program is the same as in Listing 7-4 except that it uses a filter to
exclude all .SYS files from the list. You can compare the output of these two listings to see the effect of the filter.
Listing 7-5. Using FileFilter to Filter Files
// FilteredFileList.java
package com.jdojo.io;
import java.io.File;
import java.io.FileFilter;
public class FilteredFileList {
public static void main(String[] args) {
// Change the dirPath value to list files from your directory
String dirPath = "C:\\";
File dir = new File(dirPath);
 
Search WWH ::




Custom Search