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 encoding and 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 StringBuilder object: 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对象生成的:我将数据从我的DB写到这个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:
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;
}
1 个解决方案
#1
1
File file = new File("file.xml");
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write("<file content>");
writer.close();
#1
1
File file = new File("file.xml");
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write("<file content>");
writer.close();