2012-12-13 4 views
2

JDOM 파서에서 utf-8을 사용하는 데 문제가 있습니다. 내 코드는 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); XML 파일에서 읽어 정확히이지만 아래로 쓸 때, 나는 "MIT의 freundlichen 할머니"얻을

여기

내 xml 파일의 지문 텍스트 "MIT의 freundlichen Grüßen"

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

"Mit freundlichen Grß"대신 "Mit freundlichen Grüßen"을 어떻게 쓰겠습니까? 미리 감사드립니다.

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

FileWriter 항상 플랫폼 기본 인코딩을 사용

답변

12

이 아마 문제입니다. 이것이 UTF-8이 아니라면 문제가 발생했습니다.

나는 대신 FileOutputStream을 사용하고 JDOM이 올바른 일을하도록 제안합니다. (또한 강하게 스트림에 대한 참조를 유지해야만 결국 finally 블록에서 닫을 수 있습니다 ...)

+0

감사합니다. 이제 작동합니다! – user696847

+0

+1 "finally 블록에서 닫을 수 있습니다." –

+0

Jon 's는 충분히 포괄적이기 때문에 다른 대답을 추가하지는 않겠지 만 문서 또는 XMLOutputter에는 Writer 인스턴스에 대한 출력을위한 경고 섹션이 있습니다. http : // www .jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html ...하지만 충분하지 않다고 생각합니다. 어떻게 개선 할 수 있습니까? – rolfl