如何从 Java 中的 stringbuilder 对象创建一个 utf8 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16844068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:08:21  来源:igfitidea点击:

How to create an utf8 file from stringbuilder object in Java

javafileutf-8character-encodingcodepages

提问by Alberto

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 encodingand I need UTF-8 encoding(some spanish characters aren't shown propperly on ANSI).

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

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

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

Any help is gratefully received. Thanks in advace.

非常感谢任何帮助。预先感谢。

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

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

...
    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:

我在其中生成 XML 文件的服务类:

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

createXml:

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

采纳答案by Keith

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