如何在Java中从StringBuilder对象创建一个utf8文件

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);
...

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

你能展示一下你写文件的代码吗?通常你可以提供一个额外的参数来指定编码。 - Keppil
感谢您的回复,@Keppil。我刚刚编辑了我的问题并附上了源代码。 - Alberto
尝试一下@Keith在下面的答案,我认为它应该可以工作。 - Keppil
1个回答

2
    File file = new File("file.xml");
    Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    writer.write("<file content>");
    writer.close();

非常感谢您,@Keith。我明天会尝试一下。如果有效的话,我会接受您的答案 :) - Alberto
嗨@Keith。我刚试了一下,但文件编码仍然被检测为“ANSI as UTF-8”,但现在所有字符都显示正常了。感谢您的帮助。 - Alberto
1
你可以尝试在文件开头显式地编写BOM,即\uFEFF。这可能有助于其他程序识别正确的编码。 - rossum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接