I generated xml file and I want to write it to file (with opportunity to use it later).
I generated easy xml output and wondering to know if exist some easy way to write it to file at readable format?
Code which generate xml file:
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);
}
It easy stores this file to String.
After this I tried to write it to file:
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!");
}
}
But it prints gibberish:
㰿硭氠癥牳楯渽∱⸰∠敮捯摩湧㴢啔䘭ㄶ∿㸊㱧楦琾ਠ†‼楴敭㸊.....
Generated xml has next encoding and structure:
<?xml version="1.0" encoding="UTF-16"?>
<gift>
<item>
<name>MilkChokolate</name>
<sugar>26.8</sugar>
<weight>154.8</weight>
</item>
// ...
I not sure about encoding. If is it right.
If not how to change this generation to UTF-8?
Or maybe writing xml have other nicer solution?
UPDATE:
I followed by suggestions rzymek, and changed write method:
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!");
}
}
It generate file but - this file is empty.
- How to solve this issue?