Running Java Programs with Command-Line Arguments
From command prompt
Open a command prompt and cd
into your project folder.
Then run the java
command with these arguments:
java -cp bin:lib/parserlib.jar:lib/physics.jar some.package.Main
filename1 filename2 …
-cp
specifies the classpath where Java should search for compiled code.
bin
is the folder where Eclipse compiles your code, and lib/parserlib.jar
and lib/physics.jar
are the library jar files your code (probably) depends on.
some.package.Main
is the class containing your main()
method, and some.package
is the package that contains it.
filename1 filename2 … are the list-definition filenames that you wish to load.
From Eclipse
You can also specify command-line arguments in Eclipse using the menu command Run → Run Configurations, choosing the class containing your main()
method in the dialog box, then selecting the Arguments tab.
Enter your arguments in the Program Arguments box, not the VM Argumentx box.
Using a JAR
Eclipse can also export your program as a “runnable JAR file” that contains all the code in a single file.
In Eclipse, select File → Export, then Java → Runnable JAR File.
Launch Configuration identifies which program should be exported. Find the one that runs the class containing your
main()
method.Export Destination is the name and location of the JAR file you want to generate. Put it somewhere you can find it easily to run it, like your desktop or home folder. Don’t put it in your git repo, because it isn’t source code.
For Library Handling, keep the default, “Extract required libraries into generated JAR.” This will ensure that your generated JAR file includes the code from the other jar files you depend on, like
parserlib.jar
andphysics.jar
in this project.
After you finish the dialog, open your command prompt and cd
to the folder containing the jar file you just generated.
Assuming its name is myproject.jar
, you should now be able to start your program using:
java -jar myproject.jar
You may find that your program can no longer find its ParserLib grammar file, because it is trying to read it as a file relative to the project folder, and you are no longer running the program from your project folder.
A better way would read the grammar as a classpath resource, which allows the code to be packed up in a jar, along with the grammar file, and still be able to find the grammar.
Here’s an example from the inclass code for the Parsers class.
First, put the grammar file IntegerExpression.g
in the same folder as the Java class IntegerExpressionParser.java
that needs to read it.
Then use this code in IntegerExpressionParser.java
:
InputStream grammarStream = IntegerExpression.class.openResourceAsStream("IntegerExpression.g");
return Parser.compile(grammarStream, IntegerGrammar.ROOT);
A JavaWorld article has a discussion of classpath resources.