Java Pre assign args before passing from command line
I am developing a very simple Java application, through which to take files from a folder, obtain information from them and save them in the database.
The app is launched from the command line, and I need to pass the following parameters: file_path, db_name, db_user, db_host, db_user_psw
.
When I run the check to see if all the parameters have been passed, in case a parameter is missing, I get an index out of bound exception, correctly according to java. My need is to bypass this exception and display a string indicating an error message.
For example, if all parameters except db_user_psw
are entered, instead of getting index of bound exception I would like the message "You must enter the password to access the db!"
.
My idea is to pre-assign the args to null, and once the script is run check if they are null or not. Is it possible to do this in java? I accept any advice or suggestion
- My code:
if(args[0] == null ){ System.out.println("Insert a valid Path!"); System.exit(0); }
if(args[1] == null ){ System.out.println("Insert the DB IP!"); System.exit(0);}
if(args[2] == null ){ System.out.println("Insert a DB name!"); System.exit(0);}
if(args[3] == null ){ System.out.println("Insert a DB Username!"); System.exit(0);}
if(args[4] == null ){ System.out.println("Insert User DB Password!"); System.exit(0);}
Solution 1:
When I run the check to see if all the parameters have been passed, in case a parameter is missing, I get an index out of bound exception, correctly according to java. My need is to bypass this exception and display a string indicating an error message.
Check the length of args
instead:
if(args.length == 0){ System.out.println("Insert a valid Path!"); System.exit(0); }
if(args.length == 1){ System.out.println("Insert the DB IP!"); System.exit(0);}
// ...
(You should exit with a non-zero code, in order to indicate an error)
I think you should really consider using named flags, so your command line isn't just a "meaningless" sequence of arguments that can easily be put in the wrong order. So rather than
java YourMainClass whatever blah etc
you provide something like:
java YourMainClass --file_path=whatever --db_name=blah etc
For your specific question of "Is it possible to do this in java?": You can, by copying the args array:
if (args.length < 5) args = Arrays.copyOf(args, 5);
// or
args = Arrays.copyOf(args, Math.max(5, args.length));
If args
has fewer than 5 elements, this will create an array with 5 elements, padding the "missing" elements with null.
But this is an odd and unnecessary thing to do: checking the length is easier.