Java Reference
In-Depth Information
We remove the temporary file with the rm command in the last line of
the script to avoid cluttering our /tmp directory with lots of these files.
But now we have to add code to MyClass to open the file defined by
ENVFILE and read the properties it contains. This leads us naturally to the Java
Properties class, the subject of our next section, where we'll talk more about
this example.
T HE Properties C LASS
4.4
The Javadoc page for the Properties class describes it as “a persistent set of
properties . . . saved to . . . or loaded from . . . a stream.” In other words, it is
a hashtable (a set of name/value pairs) that can be read from or written to a
stream—which typically means a file. (Other things can be streams, but for
now, think “file”.)
The great thing about name/value pairs is how readable and usable they
are. When they are written to a file, there's no fancy formatting, no fixed width
fields, no unreadable encryptions and special characters; it's just name=value .
You could say that the “ = ” and the newline are the special characters that pro-
vide all the formatting you need. It means that you can type up a properties file
with the simplest of editors, or even generate one quickly as we saw in the pre-
vious example (here we use a simple filename):
$ env > propertyfile
Properties are also easy to use. Since they're based on hashtables, there is
no searching code to write. You call a method giving it the name, it returns
the value.
If we pass in the name of the file via the -D parameter, then we can get
that filename in Java with:
System.getProperty("ENVFILE");
where ENVFILE is a name that we made up and used on the command line:
$ java -DENVFILE=propertyfile MyClass
We could also have used:
$ java MyClass propertyfile
Search WWH ::




Custom Search