我有一个文件编码问题。我有一种方法可以将我的数据库以我创建的格式导出到XML中。问题是该文件是使用ANSI编码创建的,我需要使用UTF-8编码(某些西班牙文字符未在ANSI上正确显示)。如何从Java中的stringbuilder对象创建一个utf8文件
XML文件是从StringBuilder生成的对象:我将数据从我的数据库写入此StringBuilder对象,并且当我复制了所有数据时创建了该文件。
感谢您的帮助。感谢advace。
编辑:这是我的源的一部分: 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