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

标签 java file utf-8 character-encoding codepages

我的文件编码有问题。我有一种方法可以将我的数据库导出为我创建的格式的 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;
}

最佳答案

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

关于java - 如何从 Java 中的 stringbuilder 对象创建一个 utf8 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16844068/

相关文章:

java - 在没有上下文的情况下在运行时创建 SQLite DB

javascript - 在 javascript 文件调用之后添加 time() 是一个坏主意吗?

php - 将字符串从 html 文件中的表单传递到符合 utf-8 编码的 python 脚本

iphone xml-rpc utf8 字符串

Java 包、项目、NoSuchMethod 错误

java - 使用 JAXRPC-RI Web 服务客户端时如何设置连接超时?

java - 如何在 Java 中迭代整数数组列表的元素

android - 阅读 .key 文件 android

c - 删除文本文件中的一行 (Windows)

unicode - FreeBSD 设置为 UTF-8,但似乎以 ASCII 显示