gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:58 36 4
gpt4 key购买 nike

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

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com