5

我在将 utf-8 与 JDOM 解析器一起使用时遇到问题。我的代码不会以 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 freundlichen Grüßen”,这正是从 xml 文件中读取的内容,但是当它写下来时,我得到“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üßen”而不是“Mit freundlichen Gr����”?提前致谢!

4

2 回答 2

17

大概是这个问题:

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

FileWriter始终使用平台默认编码。如果那不是 UTF-8,那你就有问题了。

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

于 2012-12-13T10:37:53.360 回答
0

我完全会选择@Jon Skeet 的答案,但如果代码在您无法修改的第 3 方库中,还有其他两个选项:

  1. 使用指定 file.encoding 的附加环境变量运行 JVM:
java -Dfile.encoding=UTF-8 … Jdom2
  1. 您可以尝试修改所Charset.defaultCharset使用的哪些存储编码FileWritter。请记住,这是一个非常hacky的解决方案,可能会在某些时候中断,我会完全避免它:
  Field field = null;
  for (Field f : Charset.class.getDeclaredFields()) {
    if (f.getName().equals("defaultCharset")) {
      field = f;
    }
  }
  field.setAccessible(true);
  Field modifiersField = Field.class.getDeclaredField("modifiers");
  modifiersField.setAccessible(true);
  modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

  field.set(null, StandardCharsets.UTF_8);

最后一句话。这两种解决方案都可能在应用程序的其他部分引入副作用,因为您正在更改某些库可能使用的默认编码。

于 2020-04-04T12:28:02.510 回答