5

JDOM パーサーで utf-8 を使用すると問題が発生します。私のコードは 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 Grüßen」を出力しますが、書き留めると「Mit 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 freundlichen Gr����」の代わりに「Mit freundlichen Grüßen」と書くにはどうすればよいですか? 前もって感謝します!

4

2 に答える 2

17

これはおそらく問題です:

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

FileWriter常にプラットフォームのデフォルトのエンコーディングを使用します。それが UTF-8 でない場合、問題が発生します。

FileOutputStream代わりに a を使用し、JDOM に正しいことをさせることをお勧めします。(また、最終ブロックで閉じることができるように、ストリームへの参照を保持する必要があると強く思います...)

于 2012-12-13T10:37:53.360 に答える