逐行读取Transformer结果(Java)

时间:2015-08-02 12:36:53

标签: java xml string line

我使用Transformer来美化并将缩进插入到原来是一条大行的XML中。 这是我的代码:

BufferedWriter br = null;
Source xmlInput = new StreamSource(inputSR);
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transformer = transformerFactory.newTransformer(); 
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);

如何将xmlOutput写入文件,逐行(不将整个字符串加载到内存中)?

1 个答案:

答案 0 :(得分:0)

使用FileOutputStream:

代替StringWriter
StreamResult xmlOutput = new StreamResult(new FileOutputStream("output.xml"))

这将以递增方式写入文件。它不一定是逐行写的(行在XML中没有多大意义),但我不明白你为什么会这么想。