A java application may accept one or more command line arguments.Command line arguments are additional parameters passed to the jar file.The program flow will be different based on what the command line argument is/are.The command line arguments have, therefore, to be processed in the main() function at the very beginning.This article with example source code will describe how to process the command line arguments.
A typical running of jar file with 3 command line arguments is as
java -jar myjar.jar arg0 arg1 arg2
Processing the command line arguments
As the values passed by the arguments are of importance to the program,I typically have a globals class where I declare these variables to store the argument data as public to be accessible anywhere in the program.The declaration is as
public class Globals { // the first argument arg0 is a file or folder name public static File Arg0FileOrFolder =null; // the second argument arg1 is a string public static String Arg1String =""; // the third argument arg2 is a string public static String Arg2String =""; // other variables ... }
Now we process the arguments at the beginning of the main() function
public static void main(String[] args) { if(args.length >0){ if(args[0].length()>0){ Globals.Arg0FileOrFolder = new File(args[0]); Globals.Arg1String = args[1]; Globals.Arg2String = args[2]; } } // additional code of the main function follows }
Once the values have been stored in the variables,we can now execute program flow based on these values.
That is all.
If you liked this article please do leave a reply and share it with friends.
Thanks.