Parsing Command-Line Arguments

Problem

You need to parse command-line options. Java doesn’t provide an API for it.

Solution

Look in the args array passed as an argument to main. Or use my GetOpt class.

Discussion

The Unix folk have had to deal with this longer than anybody, and they came up with a C-library function called getopt. [10] getopt processes your command-line arguments and looks for single-character options set off with dashes and optional arguments. For example, the command:

sort -n -o outfile myfile1 yourfile2

runs the standard sort program. The -n tells it that the records are numeric rather than textual, and the -o outfile tells it to write its output into a file named outfile. The remaining words, myfile1 and yourfile2, are treated as the input files to be sorted. On a Microsoft-based platform such as Windows 95, command arguments are set of with slashes ( / ). We will use the Unix form -- a dash -- in our API, but feel free to change the code to use slashes.

As in C, the getopt( ) method is used in a while loop. It returns once for each valid option found, returning the value of the character that was found or zero when all options (if any) have been processed.

Here is a program that uses my GetOpt class just to see if there is a -h (for help) argument on the command line:

import com.darwinsys.util.GetOpt; /** Trivial demonstration of GetOpt. If -h present, print help. */ public class GetOptSimple { public static void main(String[] args) { GetOpt go = new GetOpt("h"); ...

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.