0

下午好。我想使用 StringWriter 将新文件写入网络文件夹。任何人都可以使用下面的代码给我一些关于如何做到这一点的例子吗?这是我第一次使用 StringWriter 类。

    public static final void newOutput(Document xml) throws Exception {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter out = new StringWriter();
        tf.transform(new DOMSource(xml), new StreamResult(out));

        /*
         * need to update to write to folder
         */
        System.out.println(out.toString());

    }
}
4

1 回答 1

0
public static final void newOutput(Document xml) throws Exception {
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(xml);
    // Use StreamResult to write to a file to current directory
    StreamResult out = new StreamResult(new File("test.txt"));
    // to print to console
    // StreamResult out = new StreamResult(System.out);
    tf.transform(source, out);

    /*
     * console output is redirected to SRC folder to check format
     * need to update to write to folder
     */
    System.out.println(out.toString());

}
于 2013-12-04T21:05:49.593 回答