[英]Ensure Unix-style line endings used when generating XML on Windows with Java
我目前正在使用Java將XML文檔輸出到文件中,如下所示:
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風格的行結尾。 我怎么能這樣做?
操作系統之間的區別是因為它在內部使用了println
方法。 在保存文件之前,請更改行分隔符:
System.setProperty("line.separator", "\n");
您可以使用靜態塊。
不確定您使用的類是否使用系統屬性,但如果它們使用,則應該可以使用
System.setProperty("line.separator", "\n");
如果沒有,你將不得不像Foo Bar User在他的評論中所說,手動更換它們。
如果使用LSSerializer而不是Transformer,則可以使用LSSerializer.setNewLine來控制換行符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.