views:

1256

answers:

5

I googled for this for a while but can't seem to find it and it should be easy. I want to append a CR to then end of an XML file that I am creating with a Transformer. Is there a way to do this>

I tried the following but this resulted in a blank file?


Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "file:///ReportWiz.dtd");
xformer.transform(source, result);
OutputStream writer = new FileOutputStream(file);
Byte b = '\n';
writer.write(b);
writer.close();
A: 

I didn't know this Transformer class. But I see no connection between your writer/file variables and your xformer/source/result variables... Looks like you write only a newline.
Unless you omitted some essential part.

PhiLho
It'll be the Transformer class in jaxp.
Tom Hawtin - tackline
+1  A: 

The obvious answer is to use StreamResult with a Writer, and append your character to the writer before closing.

You appear to be trying to reopen the file to append the character. The two argument forms of the FileOutputStream constructors include an append flag.

Tom Hawtin - tackline
Using a Writer with XML libraries generally leads to trouble, since the transformer can't discover the Writer encoding in order to correctly set the encoding attribute embedded in the XML. Use an OutputStream instead.
erickson
+5  A: 

There are a couple of options here.

I assume that your result is a StreamResult that you are creating with a String specifying the destination file path. You might consider opening a FileOutputStream yourself, and constructing your StreamResult with that. Then, when the transformer is done, append the line terminator, flush, and close the stream. In the absence of constraints otherwise, I would use this approach.

If you want to re-open the file, as shown in the question, you'll need to use a FileOutputStream constructor that takes the optional append argument. Set this to true to avoid clobbering the result of the transform that was just completed.

You might also explore setting the indent output property in your transform, or including the necessary line terminator directly in your template.

erickson
+5  A: 

Simple... just add the append option:

    new FileOutputStream(f, true /* append */);
Mark Renouf
A: 

one note, make sure you write your newline character using the same character encoding you used for the xml serializaton, or your file will be broken.