2012-12-13 20 views
2

我有使用utf-8与JDOM分析器的问题。我的代码不会编写utf-8编码。 这里是代码:JDOM,umaluts和UTF-8

import java.io.FileWriter; 
import java.io.IOException; 
import org.jdom2.Element; 
import org.jdom2.output.Format; 
import org.jdom2.output.XMLOutputter; 
import org.jdom2.Document; 
import org.jdom2.JDOMException; 
import org.jdom2.input.SAXBuilder; 

public class Jdom2 { 

public static void main(String[] args) throws JDOMException, IOException { 

    String textValue = null; 
    try { 
     SAXBuilder sax = new SAXBuilder(); 
     Document doc = sax.build("path/to/file.xml"); 

     Element rootNode = doc.getRootElement(); 
     Element application = rootNode.getChild("application"); 
     Element de_DE = application.getChild("de_DE"); 
     textValue = de_DE.getText(); 
     System.out.println(textValue); 
     application.getChild("de_DE").setText(textValue); 

     Format format = Format.getPrettyFormat(); 
     format.setEncoding("UTF-8"); 
     XMLOutputter xmlOutput = new XMLOutputter(format); 
     xmlOutput.output(doc, new FileWriter("path/to/file.xml")); 

    }catch (IOException io) { 
     io.printStackTrace(); 
     } catch (JDOMException e) { 
      e.printStackTrace(); 
     } 
} 

} 

所以线的System.out.println(textValue);打印文本 “MIT freundlichenGrüßen”,这正是从XML文件中读取,但是当它写下来,我得到 “麻省理工学院freundlichen GR”

这里是我的xml文件

<?xml version="1.0" encoding="UTF-8"?> 
<applications> 
    <application id="default"> 
    <de_DE>Mit freundlichen Grüßen</de_DE> 
    </application> 
</applications> 

我将如何写作“Mit freundlichenGrüßen”而不是“Mit freundlichenGr ”? 在此先感谢!

回答

12

这可能是这个问题:

xmlOutput.output(doc, new FileWriter("path/to/file.xml")); 

FileWriter总是使用平台默认的编码。如果这不是UTF-8,你就会遇到问题。

我建议你改用FileOutputStream,让JDOM做正确的事情。 (另外,我强烈怀疑你应该保留对流的引用,以便你可以在finally块中关闭它...)

+0

谢谢,它现在可行! – user696847

+0

+1“所以你可以关闭它在一个finally块” –

+0

不会添加另一个答案,因为Jon的是足够全面的......但是,文档或XMLOutputter有一个警告部分输出到Writer实例:http:// www .jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html ...但是,我不认为这已经足够了......如何才能改进? – rolfl