O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required