Search code examples
javacommand-lineargumentsapache-commonsargs

How to connect two command line arguments?


I need to connect two command line arguments. The user is supposed to put -input "filename.txt" and/or -output "filename.txt" but I can't seem connect the -input or -output parts with the filename.

So for example the user could enter any of the following:

java classname
java classname -input filename.txt
java classname -output filename.txt
java classname -input filename.txt -output filename.txt
java classname -output filename.txt -input filename.txt

I tried this:

        for(int i = 0; i < args.length; i++){
        if(args[i].equals("-input")){
            input = args[i + 1];
        }
        else{
            //input from terminal
        }

        if(args[i].equals("-output")){
            output = args[i + 1];
        }
        else{
            //output to terminal
        }

But it's not working and seems inelegant. I have been looking into the Apache Commons CLI but I can't seem to quite figure out how that works and if there is a applicable function. Using the Apache thing or some other way is there some way I can connect the -input to the filename.txt?


Solution

  • This should work

    public static void main(String[] args) {
        String input = findArg("input", args);
        String output = findArg("output", args);
    }
    
    static String findArg(String name, String[] args) {
        for (int i = 0; i < args.length; i += 2) {
            if (args[i].equals("-" + name)) {
                return args[i + 1];
            }
        }
        return null;
    }