java append to file

2020-02-14 09:24发布

问题:

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();

回答1:

Simple... just add the append option:

    new FileOutputStream(f, true /* append */);


回答2:

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.



回答3:

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.



回答4:

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.



回答5:

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.