How to handle empty parameters in a main method java call

4.4k views Asked by At

I would like to have a dynamic way of passing in parameters to a java main method call which is done via the Command Line(cmd) to a Runnable JAR file. At the moment my main() method takes 6 parameters and sets each one to a variable before calling another method with those variables passed in.

What id like is a way to give a user the ability to pass 5 or less paramters to the command line and have it safely handle the missed parameter by setting it to null or an empty string("") value.

For example, if I ran the command below, it should know to set the missing parameters I have not specified(clientName and outputFolder), to an empty String.

java -Xmx1024m -jar MainApp.jar "Summary" **<missing>** "2015-06-07" "https://12345.bp.com/bp/" "c:\\Parameters.txt" **<missing>**

Here is the code I have for my main method:

public static void main(String[] args) {
        try {               
            String dType = args[0];
            String clientName = args[1];
            String cycleString = args[2];
            String mspsURL = args[3];
            String inputFile = args[4];
            String outputFolder = args[5];

            System.out.println("**Main Parameters passed**");
            for(String x : args) {
                System.out.println(x);
            }

            runLogic(dType, clientName, cycleString, 
                    mspsURL, inputFile, outputFolder);          
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }

Any help appreciated.

2

There are 2 answers

1
Zereges On BEST ANSWER

Suppose for example that last two are optional.

String dType = args[0];
String clientName = args[1];
String cycleString = args[2];
String mspsURL = args[3];
String inputFile = (args.length < 4 ? "default inputFile" : args[4]);
String outputFolder = (args.length < 5 ? "default outputFolder" : args[5]);
4
River On

If what you really want is a keyword for missing items, you could do:

String dType = (args[0].equals(keyword)?"":arg[0]);
String clientName = (args[1].equals(keyword)?"":arg[1]);
String cycleString = (args[2].equals(keyword)?"":arg[2]);
String mspsURL = (args[3].equals(keyword)?"":arg[3]);
String inputFile = (args[4].equals(keyword)?"":arg[4]);
String outputFolder = (args[5].equals(keyword)?"":arg[5]);

Then your input would be:

java -Xmx1024m -jar MainApp.jar "Summary" "keyword" "2015-06-07" "https://12345.bp.com/bp/" "c:\\Parameters.txt" "keyword"

Otherwise I would use the length attribute of the Array class.

Test for how long the input array is and only assign values for that many variables.

Example:

int i = args.length;
String dType = (i>0?args[0]:""); //Just do this for each argument
i--; //Then reduce counter by 1