在 Java 8 中使用 UTF-8 编码漂亮地打印和写入 XML

Pretty print and write XML with UTF-8 encoding in Java 8

我在字符串中有一个 XML 文档,我想将其漂亮打印(标签和缩进后的换行符)到一个文件中,到目前为止 的解决方案对我来说几乎是我要。

问题是,它正在使用 System.out,我想将输出写入文件,确保保留 UTF-8 编码。

下面是我修改代码的方式。它在测试 XML 字符串上运行并输出一个 XML 文件,如 所示。

我的问题是:

我是否需要刷新或关闭编写器或退出? 如果是,在代码的哪一部分?

担心不flush或者不关闭,会出现XML输出不完整的情况。

    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?" - 关闭它,是的,这也会刷新它。您可以使用 try-with-resources 更轻松地完成此操作

如果 JVM 正常关闭,它应该为您关闭这些资源,但这不是一个可靠的机制,如果没有其他原因,您应该通过良好的实践,尽快关闭您打开的所有资源你已经完成了他们。这将为 JVM 释放其他资源,而您只是不知道 JVM 何时可能关闭资源或何时可能读取您编写的资源。

类似...

try (OutputStream out = new FileOutputStream("/path/to/output.xml");
        Writer writer = new OutputStreamWriter(out, "UTF-8")) {
    pretty(document, writer, 2);
}

例如