Ensure Unix-style line endings used when generating XML on Windows with Java

心已入冬 提交于 2019-12-08 01:36:15

问题


I am currently outputting an XML document to a file in Java as follows:

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);

However, when run on Windows, this produces output with Windows-style line-endings. I would like to have Unix-style line endings produced regardless of OS. How I can do this?


回答1:


If you use LSSerializer rather than Transformer, you can use LSSerializer.setNewLine to control newlines.




回答2:


The difference between operating systems is because it is used internally the method println . Before saving the file, change the line separator:

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

You could use a static block.




回答3:


Unsure if the classes you're using use the system properties, but if they do, this should work

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

Related question but for Windows line endings

If not, you'll have to do as Foo Bar User said in his comment, replace them manually.



来源:https://stackoverflow.com/questions/19102804/ensure-unix-style-line-endings-used-when-generating-xml-on-windows-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!