Package de.stefanfrings.utils
Class CmdLineArgumentParser
java.lang.Object
de.stefanfrings.utils.CmdLineArgumentParser
Generic parser for command line arguments in Unix C-Style.
Short options start with a single dash, e.g.: -a -b -c. Long options start with a double dash, e.g.: --help.
The sequence -abc is treated as three options, like -a -b -c. All short and long options may be followed by parameters, e.g. "-i input.txt".
"-" without a character is also a valid option. "--" without a character marks the end of options. Everything after that is treated as parameters.
Usage example:
public static void main(String args[]) {
// for the result
int verbosity=0;
boolean help=false;
String importFile=null;
CmdLineArgumentParser parser=new CmdLineArgumentParser(args);
String option=parser.getNextOption();
while (option!=null) {
if (option.equals("-v") || option.equals("--verbose")) {
verbosity++; // can be repeated multiple times to increase the verbosity
}
else if (option.equals("-h") || option.equals("--help")) {
help=true;
}
else if (option.equals("-i") || option.equals("--import")) {
// after -i we expect a filename
importFile=parser.getNextParameter();
if (importFile==null) {
System.err.println("Missing file name after "+option);
}
}
option=parser.getNextOption();
}
}
- Author:
- Stefan Frings, http://stefanfrings.de/javautils
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionGets the next option from the argument list.Gets the next parameter from the argument list.
-
Constructor Details
-
CmdLineArgumentParser
Constructor- Parameters:
args- The arguments of the calling application
-
-
Method Details
-
getNextOption
Gets the next option from the argument list.- Returns:
- The next option or null if none exists
-
getNextParameter
Gets the next parameter from the argument list.- Returns:
- The next parameter or null if none exists
-