I have a XML document in a String and would like to prettyPrint (newlines after tags and indentation) it to a file, so far the solution at https://stackoverflow.com/a/25865324/3229995 is working for me almost as I want.
The problem is, it is using System.out, and I would like to write the output to a file, ensuring that the UTF-8 encoding is kept.
Below is how I modified the code. It runs and outputs an XML file on a test XML string as shown in https://stackoverflow.com/a/25865324/3229995.
My questions are:
Do I need to flush or close the writer or out? If so, at what part of the code?
I am worried that without flushing or closing, there could be cases where not the whole XML will be output.
public static void main(String[] args){
String xmlString = "<hello><from>ME</from></hello>";
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString)));
// NEW: using FileOutputStream and Writer
OutputStream out = new FileOutputStream("/path/to/output.xml");
Writer writer = new OutputStreamWriter(out, "UTF-8");
pretty(document, writer, 2);
}
private static void pretty(Document document, Writer writer, int indent) throws Exception {
document.setXmlStandalone(true);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
if (indent > 0) {
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
}
// NEW: passing the writer
Result result = new StreamResult(writer);
Source source = new DOMSource(document);
transformer.transform(source, result);
}
"Do I need to flush or close the writer or out?" - Close it, yes, this will also flush it. You can use a try-with-resources to accomplish this more easily
If the JVM closes gracefully, it should close these resources for you, but this is not a reliable mechanism and you should, if for no other reason, through good practice, close all the resources that you open as soon as you have finished with them. This will free up other resources for the JVM and you just don't know when the resource might be closed by the JVM or when the resource you've written might be read.
Something like...
try (OutputStream out = new FileOutputStream("/path/to/output.xml");
Writer writer = new OutputStreamWriter(out, "UTF-8")) {
pretty(document, writer, 2);
}
for example