The Java API exposes functionality to store persistent system properties with the Properties class. These properties can also be retrieved.
Requirements
A Java development environment, such as a Java compiler (javac
), Java runtime enviornment (JRE/java
), and a text editor.
Procedure
Java system properties (new or existing) are set and retrieved as Strings. The Properties class extends Hashtable, but Hashtable methods such as put
and putAll
are discouraged because of their type-vulnerability.
The Properties
class is located at:
java.util.Properties
You can instantiate it with:
Properties prop = System.getProperties();
if the Properties
class had been imported with the import statement. Then, you can set properties with:
prop.setProperty("Property name", "Property value");
This setProperty()
method calls the Hashtable method put
in a type-safe way. It takes the property name and value as a name/value (or key/value) pair.
You can then get a property with:
prop.getProperty("Property name");
or:
prop.getProperty("Property name", "Default Value");
The getProperty()
method takes a property name/key as a parameter and optionally a second argument which is returned if the property is not found. You can also list all properties with:
prop.list(System.out);
This takes an output stream, and can print the properties to standard output, each property separated by a newline.
You can also set values from the command line with the java command:
java -DPropertyName=ValueName -DProperty2Name="Property2 Value" Class