Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

300 HOUR 21: Reading and Writing XML Data


After the object has been filled with configuration properties, its storeToXML()
method saves it to an XMLfile. This method takes two arguments:

. AFileOutputStreamover which the file should be saved
. A comment, which can be the empty string “”if the data requires no
comment


This hour’s first project is a simple application, PropertyFileCreator, that
stores configuration properties in XMLformat. Fire up NetBeans, enter the
text from Listing 21.1 in a new empty Java file named
PropertyFileCreator, and save the file.

LISTING 21.1 The Full Text of PropertyFileCreator.java
1: importjava.io.*;
2: importjava.util.*;
3:
4: public classPropertyFileCreator {
5: public PropertyFileCreator() {
6: Properties prop = new Properties();
7: prop.setProperty(“username”, “rcade”);
8: prop.setProperty(“browser”, “Mozilla Firefox”);
9: prop.setProperty(“showEmail”, “no”);
10: try {
11: File propFile = new File(“properties.xml”);
12: FileOutputStream propStream = new
➥FileOutputStream(propFile);
13: Date now = new Date();
14: prop.storeToXML(propStream, “Created on “+ now);
15: } catch(IOException exception) {
16: System.out.println(“Error: “+ exception.getMessage());
17: }
18: }
19:
20: public static voidmain(String[] arguments) {
21: PropertyFileCreator pfc = new PropertyFileCreator();
22: }
23: }

When you run the application, it creates a properties file with three settings:
the username“rcade”, browser“Mozilla Firefox”, and showEmail“no”.
If the properties had been saved in the other format, it would look like this:
#Created on Wed Jun 15 20:56:33 EDT 2011
# Thu Wed Jun 15 20:56:33 EDT 2011
showEmail=no
browser=Mozilla Firefox
username=rcade
Free download pdf