Java add to file

I have been looking for this for a while, but cannot find it, and it should be easy. I want to add CR, and then the end of the XML file that I create with Transformer. Is there any way to do this>

I tried the following, but this led to the creation of an empty 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(); 
+3
source share
5 answers

Just ... just add the append option:

  new FileOutputStream(f, true /* append */); 
+10
source

There are a couple of options here.

I assume your result is a StreamResult , which you create with a String specifying the path to the target file. You can consider opening FileOutputStream yourself and create a StreamResult with this. Then, when the transformer is complete, add a line terminator, flush and close the stream. In the absence of restrictions, otherwise I would use this approach.

If you want to reopen the file, as shown in the question, you will need to use the FileOutputStream constructor, which accepts an optional append . Set this value to true to avoid smoothing the result of the conversion just completed.

You can also study setting the indent output property in your transform, or by including the desired line terminator directly in your template.

+5
source

The obvious answer is to use StreamResult with Writer and add your character to the record before closing.

It seems you are trying to reopen the file to add a character. Two forms of arguments to FileOutputStream constructors include the add flag.

+1
source

I did not know this Transformer class. But I do not see the connection between your files, files and your xformer / source / result variables ... It looks like you are writing only a new line.
If you have not omitted any significant part.

0
source

one note, make sure you write a newline using the same character encoding you used for the xml serializer, or your file will get corrupted.

0
source

All Articles