Program: Find

This program implements a small subset of the MS-Windows Find Filesdialog or the Unix find command. However, it has much of the structure needed to build a more complete version of either of these. It uses a custom filename filter controlled by the -n command-line option, which is parsed using my GetOpt (see Section 2.8).

import com.darwinsys.util.*; import java.io.*; import java.io.*; /** * Find - find files by name, size, or other criteria. Non-GUI version. */ public class Find { /** Main program */ public static void main(String[] args) { Find finder = new Find( ); GetOpt argHandler = new GetOpt("n:s:"); int c; while ((c = argHandler.getopt(args)) != GetOpt.DONE) { switch(c) { case 'n': finder.filter.setNameFilter(argHandler.optarg( )); break; case 's': finder.filter.setSizeFilter(argHandler.optarg( )); break; default: System.out.println("Got: " + c); usage( ); } } if (args.length == 0 || argHandler.getOptInd( )-1 == args.length) { finder.doName("."); } else { for (int i = argHandler.getOptInd( )-1; i<args.length; i++) finder.doName(args[i]); } } protected FindFilter filter = new FindFilter( ); public static void usage( ) { System.err.println( "Usage: Find [-n namefilter][-s sizefilter][dir...]"); System.exit(1); } /** doName - handle one filesystem object by name */ private void doName(String s) { Debug.println("flow", "doName(" + s + ")"); File f = new File(s); if (!f.exists( )) { System.out.println(s + " does not exist"); return; } if (f.isFile( )) doFile(f); ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.