将包含XML的String写入文件

时间:2013-12-17 11:55:52

标签: java xml file file-io

我生成了xml文件,我想将其写入文件(稍后有机会使用它)。

我生成了简单的xml输出,并想知道是否存在一种以可读格式将其写入文件的简单方法?

生成xml文件的代码:

private static void generateXml(ItemGiftBuilder builder) {
    Document doc = builder.build(items);
    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");

    LSSerializer ser = implLS.createLSSerializer();
    ser.getDomConfig().setParameter("format-pretty-print", true);

    String out = ser.writeToString(doc);
    System.out.println(out);
}

它可以轻松地将此文件存储到String。

在此之后我尝试将其写入文件:

public void writetoXmlFile(String xmlContent) {
    try {
        File theDir = new File("./output");
        if (!theDir.exists())
            theDir.mkdir();

        String fileName = "./output/" + this.getClass().getSimpleName() + "_"
                + Calendar.getInstance().getTimeInMillis() + ".xml";

        FileWriter writer = new FileWriter(new File(fileName));
        BufferedWriter out = new BufferedWriter(writer);
        writer.write(xmlContent.toString());
        out.newLine();
        writer.close();
    } catch (IOException ex) {
        System.out.println("Cannot write to file!");
    }
}

但它打印出胡言乱语:

  

㰿硭氠症牳楯渽∱⸰∠敮捯摩涌㴢啔䘭ㄶ∿㸊㱧楦琾ਠ†!楴敭㸊.....

生成的xml具有下一个编码和结构:

<?xml version="1.0" encoding="UTF-16"?>
<gift>
    <item>
        <name>MilkChokolate</name>
        <sugar>26.8</sugar>
        <weight>154.8</weight>
    </item>
    // ... 

我不确定编码。如果是的话。

如果不是如何将此代更改为UTF-8

或者写xml还有其他更好的解决方案吗?

更新

我跟着建议rzymek,并改变了写方法:

public void writetoXmlFile(String xmlContent) {
    File theDir = new File("./output");
    if (!theDir.exists())
        theDir.mkdir();

    String fileName = "./output/" + this.getClass().getSimpleName() + "_"
            + Calendar.getInstance().getTimeInMillis() + ".xml";

    try(OutputStream stream = new FileOutputStream(new File(fileName))) {
          OutputStreamWriter out = new OutputStreamWriter(stream,
          StandardCharsets.UTF_16); 
          out.write(xmlContent.toString());
          out.write("\n"); 
    } catch (IOException ex) {
        System.out.println("Cannot write to file!");
    }
}

它生成文件但是 - 此文件为空。

  • 如何解决此问题?

1 个答案:

答案 0 :(得分:1)

编写文件时指定编码:

try(OutputStream stream = new FileOutputStream(new File(fileName))) {   
    try(OutputStreamWriter out = new OutputStreamWriter(stream, StandardCharsets.UTF_16)) {
        out.write(xmlContent.toString());
        out.write("\n");
    }
} catch (IOException e) {
     System.out.println("Cannot write to file!");
     e.printStackTrace();
}