-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 :/.

mehow
  • 11
  • 6

1 Answers1

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
 }
Gal Shaboodi
  • 744
  • 1
  • 7
  • 25
  • To use it I have to add this library, is there any easier way to do this? – mehow Dec 02 '17 at 22:21
  • 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? – D.B. Dec 02 '17 at 22:45