Java Reference
In-Depth Information
The FilenameFilter need not be a separate class; case in point, the online code example
FNFilter2 implements the interface directly in the main class, resulting in a slightly shorter
file. An anonymous inner class could be used. The example FNFilterL shows it as a lambda
expression, which is shorter still:
dir_file/FNFilterL.java
// Generate the selective list, with a Lambda Expression
String [] dirs = new
new java . io . File ( dirName ). list (
( dir , s ) -> {
return
return s . endsWith ( ".java" ) ||
s . endsWith ( ".class" ) ||
s . endsWith ( ".jar" );
}
);
Arrays . sort ( dirs );
// Sort it (see Data Structuring chapter))
for
for ( String d : dirs ) {
System . out . println ( d );
// Print the list
}
In a full-scale application, the list of files returned by the FilenameFilter would be chosen
dynamically, possibly automatically, based on what you were working on. As we'll see in
Choosing a File with JFileChooser , the file chooser dialogs implement a superset of this
functionality, allowing the user to select interactively from one of several sets of files to be
listed. This is a great convenience in finding files, just as it is here in reducing the number of
files that must be examined.
Getting the Directory Roots
Problem
You want to know about the top-level directories, such as C:\ and D:\ on Windows.
Solution
Use the static method File.listRoots() .
Search WWH ::




Custom Search