Parsing Command-Line Arguments


java my_program arg1 arg2 arg3 public static void main(String[] args) {     String arg1 = args[0];     String arg2 = args[1];     String arg3 = args[2]; }



In this phrase, we store the values of three command line arguments into three separate string variables, arg1, arg2, and arg3.

Any java class can have a main() method, which is executable from the command line. The main() method accepts a String array of command-line arguments. The arguments are contained in the array in the order in which they are entered at the command line. So, to retrieve the command-line arguments, you simply have to extract the elements of the arguments array passed into the main() method.

If your application uses a lot of command-line arguments, it is wise to spend the time to write a custom command-line arguments parser to understand and handle various types of command-line arguments, such as single-character parameters, parameters that being with a dash (-), parameters that are immediately followed by another related parameter, and so on.

Note

Online, you can find many good examples of command-line argument processors to save you a lot of work. Here are two good libraries that can get you started:

http://jargs.sourceforge.net

https://args4j.dev.java.net/

Both of these are small libraries that can parse complex command-line arguments through a relatively simple interface.





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net