Java Reference
In-Depth Information
Example 3−4: FileLister.java (continued)
if (f.isDirectory()) listDirectory(fullname); // List dir
else new FileViewer(fullname).show();
// display file
}
}
}
/** A convenience method to display the contents of the parent directory */
protected void up() {
String parent = currentDir.getParent();
if (parent == null) return;
listDirectory(parent);
}
/** A convenience method used by main() */
public static void usage() {
System.out.println("Usage: java FileLister [directory_name] " +
"[-e file_extension]");
System.exit(0);
}
/**
* A main() method so FileLister can be run standalone.
* Parse command line arguments and create the FileLister object.
* If an extension is specified, create a FilenameFilter for it.
* If no directory is specified, use the current directory.
**/
public static void main(String args[]) throws IOException {
FileLister f;
FilenameFilter filter = null; // The filter, if any
String directory = null;
// The specified dir, or the current dir
// Loop through args array, parsing arguments
for(int i = 0; i < args.length; i++) {
if (args[i].equals("-e")) {
if (++i >= args.length) usage();
final String suffix = args[i]; // final for anon. class below
// This class is a simple FilenameFilter. It defines the
// accept() method required to determine whether a specified
// file should be listed. A file will be listed if its name
// ends with the specified extension, or if it is a directory.
filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.endsWith(suffix)) return true;
else return (new File(dir, name)).isDirectory();
}
};
}
else {
if (directory != null) usage(); // If already specified, fail.
else directory = args[i];
}
}
// If no directory specified, use the current directory
if (directory == null) directory = System.getProperty("user.dir");
// Create the FileLister object, with directory and filter specified.
f = new FileLister(directory, filter);
Search WWH ::




Custom Search