有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我目前正在用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风格的行尾。我怎么能做到


共 (3) 个答案

  1. # 1 楼答案

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

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

    Related question but for Windows line endings

    如果没有,你必须按照Foo Bar用户在评论中说的那样,手动替换它们

  2. # 2 楼答案

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

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

    你可以使用一个静态块

  3. # 3 楼答案

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