Filtering via FilenameFilter

The FilenameFilter functional interface can be used to filter files from a folder as well. First, we need to define a filter (for example, the following is a filter for files of the PDF type):

String[] files = path.toFile().list(new FilenameFilter() {

@Override
public boolean accept(File folder, String fileName) {
return fileName.endsWith(".pdf");
}
});

We can do the same in functional-style:

FilenameFilter filter = (File folder, String fileName) 
-> fileName.endsWith(".pdf");

Let's make this more concise:

FilenameFilter filter = (f, n) -> n.endsWith(".pdf");

In order to use this filter, we need to pass it to the overloaded File.list​(FilenameFilter filter) or File.listFiles​(FilenameFilter filter) method:

String[] files = path.toFile().list(filter);

The files array will only contain the names of the PDF files.

For fetching the result as a File[], we should call listFiles() instead of list().
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.204.0