Java Reference
In-Depth Information
Solution
Look in the
args
array passed as an argument to
main
. Or use my
GetOpt
class.
Discussion
The Unix folks have had to deal with this longer than anybody, and they came up with a C-
looks for single-character options set off with dashes and optional arguments. For example,
the command:
sort -n -o outfile myfile1 yourfile2
runs the Unix/Linux/Mac system-provided
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 Windows, command arguments are sometimes set off with slashes ( / ). We use the Unix
form—a dash—in our API, but feel free to change the code to use slashes.
Each
GetOpt
parser instance is constructed to recognize a particular set of arguments, be-
cause a given program normally has a fixed set of arguments that it accepts. You can con-
struct an array of
GetOptDesc
objects that represent the allowable arguments. For the sort
program shown previously, you might use:
GetOptDesc
[]
options
= {
new
new
GetOptDesc
(
'n'
,
"numeric"
,
false
false
),
new
new
GetOptDesc
(
'o'
,
"output-file"
,
true
true
),
};
Map optionsFound
=
new
new
GetOpt
(
options
).
parseArguments
(
argv
);
iif
(
optionsFound
.
get
(
"n"
) !=
null
null
) {
System
.
out
.
println
(
"sortType = NUMERIC;"
)
}
String outputFile
=
null
null
;
iif
((
outputFile
=
optionsFound
.
get
(
"o"
) !=
null
null
) {
System
.
out
.
println
(
"output file specified as "
+
outputFile
)
}
else
else
{
System
.
out
.
println
(
"Output to System.out"
);
}
The simple way of using
GetOpt
is to call its
parseArguments
method.