com.darwinsys.lang
Class GetOpt

java.lang.Object
  extended by com.darwinsys.lang.GetOpt

public class GetOpt
extends java.lang.Object

A class to implement UNIX-style (single-character) command line argument parsing. Originally patterned after (but not using code from) the UNIX getopt(3) program, this has been redesigned to be more Java-friendly. As a result, there are two ways of using it, which I shall very loosely call "the Unix way" and "the Java way".

  1. Original (UNIX) model:
            GetOpt go = new GetOpt("hno:");
            boolean numeric_option = false;
            String outFileName = "(standard output)";
            char c;
            while ((c = go.getopt(args)) != GetOpt.DONE) {
                switch(c) {
                case 'h':
                    doHelp(0);
                    break;
                case 'n':
                    numeric_option = true;
                    break;
                case 'o':
                    outFileName = go.optarg();
                    break;
                default:
                    System.err.println("Unknown option character " + c);
                    doHelp(1);
                }
            }
            System.out.print("Options: ");
            System.out.print("Numeric: " + numeric_option + ' ');
            System.out.print("Output: " + outFileName + "; ");
            System.out.print("Inputs: ");
            if (go.getOptInd() == args.length) {
                doFile("(standard input)");
            } else for (int i = go.getOptInd(); i < args.length; i++) {
                doFile(args[i]);
            }
     
  2. Newer (Java) model, which allows long-named options:
            boolean numeric_option = false;
            boolean errs = false;
            String outputFileName = null;
    
            GetOptDesc options[] = {
                new GetOptDesc('n', "numeric", false),
                new GetOptDesc('o', "output-file", true),
            };
            GetOpt parser = new GetOpt(options);
            Map optionsFound = parser.parseArguments(argv);
            Iterator it = optionsFound.keySet().iterator();
            while (it.hasNext()) {
                String key = (String)it.next();
                switch (key.charAt(0)) {
                    case 'n':
                        numeric_option = true;
                        break;
                    case 'o':
                        outputFileName = optionsFound.get(key);
                        break;
                    case '?':
                        errs = true;
                        break;
                    default:
                        throw new IllegalStateException(
                        "Unexpected option character: " + key);
                }
            }
            if (errs) {
                System.err.println("Usage: GetOptDemo [-n][-o file][file...]");
            }
            System.out.print("Options: ");
            System.out.print("Numeric: " + numeric_option + ' ');
            System.out.print("Output: " + outputFileName + "; ");
            System.out.print("Input files: ");
            List files = parser.getFilenameList();
            for (String file : files) {
                System.out.print(file);
                System.out.print(' ');
            }
            System.out.println();
            }
     

This class is not threadsafe; it is expected to be used only from main().

For another way of dealing with command lines, see the Jakarta Commons Command Line Interface.

Version:
$Id: GetOpt.java,v 1.28 2006/08/07 15:30:02 ian Exp $
Author:
Ian F. Darwin, http://www.darwinsys.com/

Field Summary
protected  boolean done
          Internal flag - whether we are done all the options
static int DONE
          Public constant for "no more options"
protected  java.util.List<java.lang.String> fileNameArguments
          The List of File Names found after args
protected  java.lang.String optarg
          The current option argument.
protected  int optind
          Where we are in the options
protected  GetOptDesc[] options
          The set of characters to look for
 
Constructor Summary
GetOpt(GetOptDesc[] opt)
          Construct a GetOpt parser, given the option specifications in an array of GetOptDesc objects.
GetOpt(java.lang.String patt)
          Construct a GetOpt parser, storing the set of option characters.
 
Method Summary
 java.util.List<java.lang.String> getFilenameList()
          Get the list of filename-like arguments after options; only for use if you called parseArguments.
 char getopt(java.lang.String[] argv)
          The true heart of getopt, whether used old way or new way: returns one argument; call repeatedly until it returns DONE.
 int getOptInd()
          Return optind, the index into args of the last option we looked at
 java.lang.String optarg()
          Retrieve the current option argument; UNIX variant spelling.
 java.lang.String optArg()
          Retrieve the current option argument; Java variant spelling.
 java.util.Map<java.lang.String,java.lang.String> parseArguments(java.lang.String[] argv)
          Modern way of using GetOpt: call this once and get all options.
 void rewind()
          Reset this GetOpt parser
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

fileNameArguments

protected java.util.List<java.lang.String> fileNameArguments
The List of File Names found after args


options

protected final GetOptDesc[] options
The set of characters to look for


optind

protected int optind
Where we are in the options


DONE

public static final int DONE
Public constant for "no more options"

See Also:
Constant Field Values

done

protected boolean done
Internal flag - whether we are done all the options


optarg

protected java.lang.String optarg
The current option argument.

Constructor Detail

GetOpt

public GetOpt(GetOptDesc[] opt)
Construct a GetOpt parser, given the option specifications in an array of GetOptDesc objects. This is the preferred constructor.


GetOpt

public GetOpt(java.lang.String patt)
Construct a GetOpt parser, storing the set of option characters. This is a legacy constructor for backwards compatibility. That said, it is easier to use if you don't need long-name options, so it has not been and will not be marked "deprecated".

Method Detail

optarg

public java.lang.String optarg()
Retrieve the current option argument; UNIX variant spelling.


optArg

public java.lang.String optArg()
Retrieve the current option argument; Java variant spelling.


rewind

public void rewind()
Reset this GetOpt parser


parseArguments

public java.util.Map<java.lang.String,java.lang.String> parseArguments(java.lang.String[] argv)
Modern way of using GetOpt: call this once and get all options.

This parses the options, returns a Map whose keys are the found options. Normally followed by a call to getFilenameList().
Side effect: sets "fileNameArguments" to a new List

Returns:
a Map whose keys are Strings of length 1 (containing the char from the option that was matched) and whose value is a String containing the value, or null for a non-option argument.

getFilenameList

public java.util.List<java.lang.String> getFilenameList()
Get the list of filename-like arguments after options; only for use if you called parseArguments.


getopt

public char getopt(java.lang.String[] argv)
The true heart of getopt, whether used old way or new way: returns one argument; call repeatedly until it returns DONE. Side-effect: sets globals optarg, optind


getOptInd

public int getOptInd()
Return optind, the index into args of the last option we looked at



Copyright © 1996-2004 Ian F. Darwin. See license.html for usage license.