/** * Args.java * * @author Jeff Ondich * @version 4/2/05 * * Based on a C++ program written during class in 2004 to * illustrate one approach to parsing command-line arguments. The * basic approach is: (1) set your default behaviors, (2) scan * through the arguments to set non-default behaviors, and * (3) execute the specified behaviors. * * The program's job, such as it is, is to change its input to * upper case, sending the output to standard out. The input * can come from either a file or standard input, and there are * usage and version flags that override the input->output * and just print suitable messages. */ import java.util.*; import java.io.*; public class Args { public static void main( String[] args ) { // Set default behaviors. String fileName = null; boolean printUsage = false; boolean printVersion = false; for( int k=0; k < args.length; k++ ) { if( args[k].equals( "-u" ) ) printUsage = true; else if( args[k].equals( "-v" ) ) printVersion = true; else if( k < args.length - 1 ) { // A file for input can only be the last argument. // Thus, if we find something that isn't a valid // option before the last argument, we have an // invalid command line. printUsage = true; } else // There's a single file specified. fileName = args[k]; } if( printUsage || printVersion ) { if( printVersion ) printVersionStatement(); if( printUsage ) printUsageStatement(); System.exit( 1 ); } else { Scanner in = null; if( fileName == null ) in = new Scanner( System.in ); else { try { File inputFile = new File( fileName ); in = new Scanner( inputFile ); } catch( IOException e ) { System.err.println( "Can't open " + fileName ); System.exit( 1 ); } } capitalize( in ); } } public static void printUsageStatement() { System.err.println( "Usage: java Args [-u] [-v] [file]" ); } public static void printVersionStatement() { System.err.println( "Args, version 0.00001" ); } public static void capitalize( Scanner in ) { while( in.hasNextLine() ) { String line = in.nextLine(); System.out.println( line.toUpperCase() ); } } }