本人在Windows系统下Eclipse工作的时候,输出xml文件的时候遇到了这么一个奇怪的编码问题。代码如下
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING,"GBK");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file + "\\" + project.getName() + ".xml"));
transformer.transform(source, result);在Windows环境下我用EmEditor查看xml文件,编码为GB2132,但是当把文件移动Redhat(locale GBK)的时候,中文就是乱码。
但是我朦胧的把问题解决了,解决办法大致就是把此文件格式化一遍,采用了dom4j插件。
public static void formatXMLFile(String filePath, String encode) {
try {
        SAXReader read = new SAXReader();
org.dom4j.Document doc = read.read(new File(filePath));
XMLWriter writer = null;
org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
format.setEncoding(encode);
writer = new XMLWriter(new FileOutputStream(new File(filePath)), format);
writer.write(doc);
writer.close();
}catch(Exception e) {
    e.printStackTrace();
}
}
明明setOutputProperty方法就是明确设置了实际输出的编码格式啊,到底是怎么回事?
请赐教!