< Day Day Up > |
Using System PropertiesOne obscure feature of the JDK is that the command-line option -D can modify the performance of the Java class library. If you have used other programming languages prior to learning Java, you might be familiar with environment variables, which provide information about the operating system in which a program is running. An example is the CLASSPATH setting, which indicates the folders in which the Java interpreter should look for a class file. Because different operating systems have different names for their environment variables, they cannot be read directly by a Java program. Instead, Java includes a number of different system properties that are available on any platform with a Java implementation. Some properties are used only to get information. The following system properties are among those that should be available on any Java implementation:
Other properties can affect how the Java class library performs when being used inside a Java program. An example of this is the java.io.tmpdir property, which defines the folder that Java's input and output classes use as a temporary workspace. A property can be set at the command line by using the –D option followed by the property name, an equal sign, and the new value of the property, as in this command: java -Duser.timezone=Asia/Jakarta Auctioneer The use of the system property in this example sets the default time zone to "Asia/Jakarta" before running the Auctioneer class. This affects any Date objects in a Java program that do not set their own zone. These property changes are not permanent; they only apply to that particular execution of the class and any classes that it uses.
You also can create your own properties and read them using the getProperty() method of the System class, which is part of the java.lang package. Listing B.4 contains the source code of a simple program that displays the value of a user-created property. Listing B.4. The Full Text of ItemProp.java1: class ItemProp { 2: public static void main(String[] arguments) { 3: String n = System.getProperty("item.name"); 4: System.out.println("The item is named " + n); 5: } 6: } If this program is run without setting the item.name property on the command line, the output is the following: The item is named null The item.name property can be set using the -D option, as in this command: java -Ditem.name="Microsoft Bob" ItemProp The output is the following: The item is named Microsoft Bob The -D option is used with the Java interpreter. To use it with the appletviewer as well, all you have to do differently is precede the -D with -J. The following command shows how this can be done: appletviewer -J-Dtimezone=Asia/Jakarta AuctionSite.html This example causes appletviewer to use the default time zone "Asia/Jakarta" with all applets on the web page AuctionSite.html. |
< Day Day Up > |