13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

4.4 The Properties Class109We remove the temporary file with the rm command in the last line ofthe 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 byENVFILE and read the properties it c<strong>on</strong>tains. This leads us naturally to the JavaProperties class, the subject of our next secti<strong>on</strong>, where we’ll talk more aboutthis example.4.4THE Properties CLASSThe Javadoc page for the Properties class describes it as “a persistent set ofproperties . . . saved to . . . or loaded from . . . a stream.” In other words, it isa hashtable (a set of name/value pairs) that can be read from or written to astream—which typically means a file. (Other things can be streams, but fornow, think “file”.)The great thing about name/value pairs is how readable and usable theyare. When they are written to a file, there’s no fancy formatting, no fixed widthfields, no unreadable encrypti<strong>on</strong>s and special characters; it’s just name=value.You could say that the “=” and the newline are the special characters that provideall the formatting you need. It means that you can type up a properties filewith the simplest of editors, or even generate <strong>on</strong>e quickly as we saw in the previousexample (here we use a simple filename):$ env > propertyfileProperties are also easy to use. Since they’re based <strong>on</strong> hashtables, there isno searching code to write. You call a method giving it the name, it returnsthe value.If we pass in the name of the file via the -D parameter, then we can getthat filename in Java with:System.getProperty("ENVFILE");where ENVFILE is a name that we made up and used <strong>on</strong> the command line:$ java -DENVFILE=propertyfile MyClassWe could also have used:$ java MyClass propertyfile

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!