2013-05-30 130 views
2

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

你能告诉我们你写文件的代码吗?通常你可以提供一个编码作为额外的参数。 – Keppil

+0

感谢您的回复@Keppil。我刚刚使用源代码编辑了我的问题。 – Alberto

+0

下面试试@ Keith的答案,我认为它应该可以工作。 – Keppil

回答

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

非常感谢@Keith。我明天会尝试。如果它有效,我会接受你的回答:) – Alberto

+0

Hi @Keith。我刚刚尝试过,但文件编码仍然被检测为“ANSI as UTF-8”,但现在所有字符都已正确显示。谢谢你的帮助。 – Alberto

+0

您可以尝试在文件开头明确写入BoM,'\ uFEFF'。这可能有助于其他程序识别正确的编码。 – rossum