Java Reference
In-Depth Information
this, and I found it quite useful. By using listFiles() , which constructs a new File object
for each name, you could print the size of each, as per the DOS dir command or the Unix ls -
l command (see Getting File Information ) . Or you could figure out whether each is a file, a
directory, or neither. Having done that, you could pass each directory to your top-level func-
tion, and you'd have directory recursion (the Unix find command, or ls -R , or the DOS DIR
/S command).
A more flexible way to list filesystem entries is with list(FilenameFilter ff) . File-
nameFilter is a little interface with only one method: boolean accept(File inDir ,
String fileName) . Suppose you want a listing of only Java-related files ( *.java , *.class ,
*.jar , etc.). Just write the accept() method so that it returns true for these files and false for
any others. Here is the Ls class warmed over to use a FilenameFilter instance (my
OnlyJava class implements this interface) to restrict the listing:
public
public class
class FNFilter
FNFilter {
public
public static
static void
void main ( String argh_my_aching_fingers []) {
// Generate the selective list, with a one-use File object.
String [] dirs = new
new java . io . File ( "." ). list ( new
new OnlyJava ());
Arrays . sort ( dirs );
// Sort it (Data Structuring chapter))
for
for ( String d : dirs ) {
System . out . println ( d );
// Print the list
}
}
/** This class implements the FilenameFilter interface.
* The Accept method returns true for .java, .class and .jar files.
*/
private
private static
static class
class OnlyJava
OnlyJava implements
implements FilenameFilter {
public
public boolean
boolean accept ( File dir , String s ) {
iif ( s . endsWith ( ".java" ) ||
s . endsWith ( ".class" ) ||
s . endsWith ( ".jar" )) {
return
return true
true ;
}
// others: projects, ... ?
return
return false
false ;
}
}
}
Search WWH ::




Custom Search