DirList.java
Download DirList.java
1: // Directory listing program. If no directories are listed on the
2: // command line then a list for the user's home directory is made.
3: // For now the output is plain text sent to stdout. For each directoy
4: // all files within are listed. Subdirectories are listed recursively.
5: // Todo: Sort files in list, show complete (or connonical) name for
6: // tops, show output in a swing JTree.
7: //
8: // Written 2001 by Wayne Pollock, Tampa Florida USA.
9:
10: import java.io.*;
11:
12: public class DirList
13: {
14: private static String [] tops; // The top level dirs/files to list
15:
16: public static void main ( String [] args ) throws IOException
17: { if ( args.length == 0 )
18: { tops = new String[1];
19: tops[0] = System.getProperty( "user.dir" );
20: } else
21: { tops = args;
22: }
23: StringBuffer indent = new StringBuffer();
24: for ( int i = 0; i < tops.length; ++i )
25: list( new File( tops[i] ), indent );
26: }
27:
28: static void list ( File f, StringBuffer indent ) throws IOException
29: { if ( ! fileExists( f ) ) return;
30: System.out.println( indent + f.getName() );
31: if ( f.isFile() ) return;
32:
33: // Must be a directory, so process each file/dir in it:
34: indent.append( " " ); // indent one level
35: File [] files = f.listFiles();
36: for ( int i = 0; i < files.length; ++i )
37: { if ( ! fileExists( files[i] ) ) continue;
38: if ( files[i].isDirectory() )
39: list( files[i], indent ); // recursively process subdir
40: else
41: System.out.println( indent + files[i].getName() );
42: }
43: }
44:
45: static boolean fileExists ( File f )
46: { if ( ! f.exists() )
47: { System.out.println( "DirList: \"" + f.getName() +
48: "\" does not exist." );
49: return false;
50: }
51: return true;
52: }
53: }