0

I'm trying to write a Java wrapper which will internally call a shell script passing the required arguments to the script. My class would be called as follows:

MyClass --arg1 value1 --arg2 value2 --arg3 value3 

I would like to know what is the best way to parse these arguments? My current approach is as follows:

  • Split the space separated arguments and store them in an array
  • Go through the array and check for --argX and then pick the next element as the value for that argument.

However, my current approach seems menial to me and I'm looking for better ways of doing this.

1
  • 1
    Something like this should do the job. It's up to you to develop it further. Note that in Java you need to use \\w instead of \w. Happy coding ! Commented May 24, 2013 at 0:13

3 Answers 3

2

You can pass arguments to your Java programs using public static void main (String[] args) where String[] args will take the values.

For example: YourClass --arg1 1 --arg2 2 --arg3 "Hello world" will store in your args array {"--arg1", "1", "--arg2", "2", "--arg3", "Hello world"} and you should be able to run your code using this input and some kind of "Command parser" class where you analyze what has been the input chose to run the program.

Sign up to request clarification or add additional context in comments.

Comments

2

How about this:

Passing in key value pairs

java MainClass -Dkey1=value1 -Dkey2=value2

Using

System.getProperty("key1")

you can access the value.

Comments

1

The Apache Commons CLI library provides an API for parsing command line options passed to programs.

See an example in Inspired by Actual Events: Command-line Parsing with Apache Commons CLI

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.