Java:将 StreamResult 保存到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1937684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:35:42  来源:igfitidea点击:

Java: Saving StreamResult to a file

javaxmlfilestreamsax

提问by Todd

I am doing some data conversion(like csv) to xml with SAX then using transformer in Java. The result is in StreamResult, and I am trying to save this result to a file.xml but I can't find way to save StreamResult into file. am I doing this all wrong?

我正在使用 SAX 将一些数据转换(如 csv)转换为 xml,然后在 Java 中使用转换器。结果在 StreamResult 中,我试图将此结果保存到 file.xml,但我找不到将 StreamResult 保存到文件中的方法。我做这一切都错了吗?

采纳答案by Carl Smotricz

Your StreamResultshould be created on the basis of a file, e.g.

StreamResult应该基于文件创建,例如

StreamResult sr = new StreamResult(new File("/my/file.xml"));

If you give your Transformersuch a StreamResult, it will write its result directly into the file you specified.

如果你给你Transformer这样的 a StreamResult,它会直接将结果写入你指定的文件中。

回答by TofuBeer

I am not familiar with the API... but does this linkgive you what you are after?

我不熟悉 API ......但是这个链接是否给了你你想要的东西?

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xmlString = result.getWriter().toString();
System.out.println(xmlString);