3

我的文件编码有问题。我有一种方法可以将我的数据库以我创建的格式导出为 XML。问题是文件是用ANSI 编码创建的,我需要UTF-8 编码(一些西班牙字符在 ANSI 上没有正确显示)。

XML 文件是从StringBuilder对象生成的:我将数据库中的数据写入此 StringBuilder 对象,当我复制了所有数据后,我创建了文件。

任何帮助都将不胜感激。预先感谢。

编辑:这是我的来源的一部分: XMLBuilder 类:

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

我生成 XML 文件的服务类:

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

创建 XML

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;
}
4

1 回答 1

2
    File file = new File("file.xml");
    Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    writer.write("<file content>");
    writer.close();
于 2013-05-30T19:32:49.853 回答