How to create an utf8 file from stringbuilder object in Java

Alberto picture Alberto · May 30, 2013 · Viewed 11.8k times · Source

I have a problem with file encoding. I have a method which exports my DB to a XML in a format I created. The problem is that the file is created with ANSI encoding and I need UTF-8 encoding (some spanish characters aren't shown propperly on ANSI).

The XML file is generated from a StringBuilder object: I write the data from my DB to this StringBuilder object and when I have copied all the data I create the file.

Any help is gratefully received. Thanks in advace.

Edit: This is part of my source: XMLBuilder class:

...
    public XmlBuilder() throws IOException {
      this.sb = new StringBuilder();
    }
...
    public String xmlBuild() throws IOException{
      this.sb.append(CLOSE_DB);
      return this.sb.toString();
    }
...

Service class where I generate the XML file:

XmlBuilder xml = new XmlBuilder();
... (adding to xml)...
xmlString = xml.build();
file = createXml(xmlString);
...

createXml:

public File createXml(String textToFile) {
  File folder = new File("xml/exported/");
  if (!folder.exists()) {
      folder.mkdirs();
  }
  file = new File("xml/exported/exportedData.xml");

  try (FileOutputStream fop = new FileOutputStream(file)) {

    // if file doesn't exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }
    //if file exists, then delete it and create it
    else {
        file.delete();
        file.createNewFile();
    }

    // get the content in bytes
    byte[] contentInBytes = textToFile.getBytes();

    fop.write(contentInBytes);
    fop.flush();
    fop.close();

    System.out.println("Done");

  } catch (IOException e) {
    e.printStackTrace();
  }
  return file;
}

Answer

Keith picture Keith · May 30, 2013
    File file = new File("file.xml");
    Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    writer.write("<file content>");
    writer.close();