Using Program Parameters in Java Part-2

Alternatives to the command line

Giving parameters on the command line is not always the best way to enter properties for your program. A typical situation where something else is needed is when your Java program isn’t invoked through a main method. An good example is when you have coded a servlet for a web server. In this situation you may use the web.xml file to specify the parameters you need.

Another servlet example could be when you’re using Struts. In this case you don’t code the servlet, so it might be more logical to place the parameter on the Struts action. You may then use the parameter attribute on the action element in the struts-config file for entering parameters.

If you have access to the command line where the VM is initiated you may use the -D option to pass parameters to your own code. For example:

mykey and myvalue are available through the Java system properties interface, which provides a nice segue to the next topic: the Properties class.

The Java Properties class

The Properties class is an interface to the file system–or rather a Java InputStream. To read parameters from a file you first enter your information in the file as key-value pairs:

Here’s the code needed to read the value for the mykey parameter from a file called my.properties (for the Java program to find the properties file it should be placed in the classpath).

This is a nice way to specify parameters to your program. You may create several property files if this is more convenient for your application, and why not combine this solution with CLI and specify the name of the property file as a command line option:

A complete main program that combines CLI with a property file looks like this:

System properties

I briefly mentioned that you could enter key/value pairs to the Java VM like this:

Such values may be retrieved from the System Properties instance like this:

More key-value pairs are entered by repetition:

This solution could be used when your code is used by a main program that can’t be modified.

In the CLI section I mentioned that CLI also allows you to specify key-value pairs. This is useful if you for some reason don’t know the parameter names in advance. Here’s a handy way of specifying a key-value option called “X”:

Note that you must separate the -X parameter from its values by at least one blank space. Here’s the output from this code:

You get 4 values back in a String array.