0

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?
1
  • I would suggest to split this question into at least two: (1) Writing a String containing XML to a file. (2) Creating a file with a unique name. (2) is quite independent on (1). Commented Dec 17, 2013 at 12:08

1 Answer 1

1

Specify the encoding when writing the file:

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

It causes another problem. This prints empty file. I updated question.
Let's autoclose out as well. Updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.