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

时间:2013-09-30 20:05:05

标签: java xml windows line-endings

我目前正在使用Java将文档输出到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);

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

3 个答案:

答案 0 :(得分:4)

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

System.setProperty("line.separator", "\n");

您可以使用静态阻止。

答案 1 :(得分:2)

不确定您使用的类是否使用系统属性,但如果它们使用,则应该可以使用

System.setProperty("line.separator", "\n");

Related question but for Windows line endings

如果没有,你必须像Foo Bar User在评论中所说的那样,手动更换它们。

答案 2 :(得分:2)

如果您使用LSSerializer而不是Transformer,则可以使用LSSerializer.setNewLine来控制换行符。