-2

I cannot find easy solution to resolve my problem in Java. I have to run JAR file using command line with parametres.

I know how to do it like below, and it's working fine:

java -jar filename.jar argument1 argument2 etc. For example: java -jar file.jar 50 10

But, what should I do, it I heve to use some parameters? For example: java -jar file -width 50 -height 10

Is it possible?

[Edit] I cannot use external libraries.

Any similar answers are not so easy for beginner, some of them doesn't work for me. I'm not so stupid to open ticket first, I was looking for answer two days. But if you still think that this is duplicate just delete all posts in this topic :/.

2
  • There are libraries to help you with this. Commented Dec 2, 2017 at 22:05
  • What libraries? Commented Dec 2, 2017 at 22:09

1 Answer 1

2

You can use Apache Common CLI

// create Options object
Options options = new Options();
 // add t option
options.addOption("t", false, "display current time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
 if(cmd.hasOption("t")) {
     // print the date and time
 } else {
     // print the date
 }
Sign up to request clarification or add additional context in comments.

2 Comments

To use it I have to add this library, is there any easier way to do this?
If you don't want to add a library you can write your own parsing algorithm. As you said you have already been able to use program arguments before: "I know how to do it like below, and it's working fine: java -jar filename.jar argument1 argument2 etc" For your new requirement argument1 = "-width", argument2 = "50" etc. So to avoid using a 3rd party library you can write your own parsing to figure out how to associate names and values, but why reinvent the logic when it's already available to you for free?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.