确保在使用 Java 在 Windows 上生成 XML 时使用 Unix 样式的行结尾

Rya*_*ard 2 java xml windows line-endings

我目前正在将 XML 文档输出到 Java 文件中,如下所示:

final Document xmldoc = toXMLDocument(docTheory);

// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(xmldoc);
StreamResult result = new StreamResult(file);

transformer.transform(source, result);
Run Code Online (Sandbox Code Playgroud)

但是,在 Windows 上运行时,这会生成带有 Windows 样式行结尾的输出。无论操作系统如何,我都希望生成 Unix 风格的行尾。我怎么能做到这一点?

Pau*_*gas 5

操作系统之间的区别是因为它是内部使用的方法println。在保存文件之前,更改行分隔符:

System.setProperty("line.separator", "\n");
Run Code Online (Sandbox Code Playgroud)

您可以使用静态块。