juliensaad
juliensaad

Reputation: 2059

How do I create a java project that takes options at runtime (i.e. -p or -f)

I want to create a jar file that can be run with options like that:

java -jar EXEC_NAME
java -jar -p EXEC_NAME
java -jar -p -f "path_to_file_name" EXEC_NAME

I know how to pass args like path_to_file_name and read them, but how can I configure my project to pass a

-p 

option?

I am working in Eclipse.

Upvotes: 0

Views: 66

Answers (4)

They show up in the string array passed in in the call to main.

public static void main(String[] args)

Here it would be args

for "-p -q" you would have a two-element string array just like

String[] args = new String{"-p", "-q"};

If any of your options are complex, consider using a library instead.

Upvotes: 0

buc
buc

Reputation: 6358

In Eclipse, you can right click on your project, select Run As / Run Configurations. There will be a tab panel named Arguments where you can set the command line arguments passed to your program when you run it from inside Eclipse.

Upvotes: 1

user2403009
user2403009

Reputation:

The first thing of note. Flags that should be passed to the application should come after "EXEC_NAME".

java -jar EXEC_NAME -p -f "path_to_file_name"

The second thing of note is your main(String[]) method. The variable there (usually named args) is an array containing all input to the right of "EXEC_NAME". So in the case of the example above. args[0] would be "-p", args[1] would be "-f", and args[2] would be "path_to_file_name".

I hope that helps you. If you need further help feel free to contact me and I will do my best to respond in a timely manner.

Upvotes: 1

bmargulies
bmargulies

Reputation: 100151

Java command-line arguments are passed as parameters to the main method. To use java -jar, you designate a class as your Main-Class in your MANIFEST.MF file. That class has a method named main, and such parameters are passed to it when it is called.

Eclipse has nothing to do with this, it's core Java behavior.

Upvotes: 2

Related Questions