Java Reference
In-Depth Information
Writing the XML File
Before we start, let's add a few constants to our
Constants
interface in the Sketcher code:
String QUOTE
_
ENTITY = """;
char QUOTE = '\"';
char NEWLINE = '\n';
char TAG
_
START = '<';
char TAG
_
END = '>';
String EMPTY
_
TAG
_
END = "/>";
String END
_
TAG
_
START = "</";
We will standardize on using a double quote as a string delimiter in the XML that we will generate. We will
therefore substitute the
QUOTE
_
ENTITY
constant for any double quotes that appear in the text for a Sketcher
Text
element. The other constants will come in useful when we are assembling XML markup.
We will make the
saveXMLSketch()
method a member of the
SketchFrame
class. This method will
obtain a
FileChannel
object for the
File
object that is passed as an argument. The
FileChannel
object can then be used to write the XML to the file. Here's how we can define this method:
private void saveXMLSketch(File outFile) {
FileOutputStream outputFile = null; // Stores an output stream reference
try {
outputFile = new FileOutputStream(outFile); // Output stream for the file
FileChannel outChannel = outputFile.getChannel(); // Channel for file stream
writeXMLFile(theApp.getModel().createDocument(), outChannel);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
JOptionPane.showMessageDialog(SketchFrame.this,
"Sketch file " + outFile.getAbsolutePath() + " not found.",
"File Output Error",
JOptionPane.ERROR
_
MESSAGE);
return; // Serious error - return
}
}
This calls another method that we have yet to write. The
writeXMLFile()
method will assemble the
XML from the
Document
object passed as the first argument, and write that to the
FileChannel
referenced by the second argument.
We don't really expect to end up in the
catch
block. If we do, something is seriously wrong
somewhere. Don't forget to import the
FileChannel
class name. The
import
statement you must add
to
SketchFrame
is:
import java.nio.channels.FileChannel;