2013-09-30 36 views
2

在Windows上生成XML时,我目前输出的XML文档Java中的文件,如下所示使用Unix风格的行结束符:确保与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风格的行结尾。我如何做到这一点?

+0

我不确定这是否是您的最佳解决方案,但'string.replaceAll(“\ r \ n”,“\ n”)'会做 –

+0

如果答案有帮助,您可以[接受它](http ://meta.stackexchange.com/a/5235/227183)。 –

回答

2

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

+0

这不适用于Java 6和7. https://community.oracle.com/message/6853346#6853346 – basin

2

不确定,如果你使用使用该系统的特性,但类,如果他们这样做,这应该工作

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

Related question but for Windows line endings

如果不是这样,你必须做,因为富栏用户在他的评论中说,手动替换它们。

+0

它适用于'TransformerFactory' API –

4

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

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

你可以使用一个静态块。