6.031 — Software Construction
Spring 2017

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 norn.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 is ParserLib. Note that you don’t need to include httpserver.jar on the classpath because it’s actually built into Java.

norn.Main is the class containing your main() method.

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 your email.Main program 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. For this project, it’s likely to be something like Main - norn2.

  • Export Destination is the JAR file you want to generate. norn.jar is a good choice. 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 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 norn.jar, you should now be able to start your program using:

java -jar norn.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.