JDom输出UTF-8的XML完美解决方法

完美的解决方法从辟谣开始:

1)JDOM是否生成UTF-8的文件与Format是否设置无关,只有输出其他字符编码才需要设置,见下面的注释。

2)JDOM输出UTF-8文件乱码的根本原因并非在JDOMAPI,而是在JDK。

具体描述:

JDOM的输出类XMLOutputter有两个output接口,除了都具有一个Document参数外,分别接受Writer和OutputStream参数。

这给我们一个错觉,两个接口可以任意使用。

首先我们用output(doc,System.out)来做测试,此时得到乱码,

然后我们改为output(doc,new PrintWriter(System.out))来测试,输出不是乱码,

也就是说在控制台的时候一定要用一个Writer接口包装一下。

然后我们用output(doc,new FileWriter(path))来做测试,结果却得到乱码,

然后我们改为output(doc,new FileOutputStream(path))来测试,输出不是乱码,

也就是说在输出文件的时候一定要用一个OutputStream接口包装一下。

疯了吧?呵呵,很搞笑是吧。经过到JDOM的源码中调试,发现没有任何问题,问题出在了JDK里面。

JDK内的对应接口处理:

1)PrintWriter类有参数为OutputStream的构造方法,因此可以从System.out包装到PrintWriter

2)FileWriter类没有参数为OutputStream的构造方法,因此不能从FileOutputStream包装到FileWriter

3)如果PrintWriter类用了参数为Writer的构造方法(Writer实现为FileWriter),最后输出也是乱码

4)如果用一个FileOutputStream来包装一个控制台输出,也是乱码

因此,对于JDK内的各种输出体系,各种InputStream、OutputStream、reader和writer要充分认识,否则极容易出现一些意想不到的问题。

测试的JDOM版本:1.0、1.1

测试代码:

    import java.io.File;    import java.io.FileOutputStream;    import java.io.FileWriter;    import java.io.PrintWriter;    import java.util.HashMap;    import org.jdom.Document;    import org.jdom.Element;    import org.jdom.output.Format;    import org.jdom.output.XMLOutputter;    public class BuildXML {     public static void main(String[] args) throws Exception{      File xmlfile=new File("C://EditTemp//xml//abc.xml");      //中文问题 //GBK 是没有问题的,但UTF-8就是有问题的      //原因:      //1)对于磁盘文件,必须使用输出流 FileOutputStream      //     FileWriter ut=new FileWriter(xmlfile);会导致乱码      //2)对于控制台输出,则必须使用PrintWriter,如果直接使用System.out也会出现乱码      //     PrintWriter ut=new PrintWriter(System.out);      FileOutputStream ut=new FileOutputStream(xmlfile);         Element eroot=new Element("root");         eroot.addContent((new Element("code")).addContent("代码"));         eroot.addContent((new Element("ds")).addContent("数据源"));         eroot.addContent((new Element("sql")).addContent("检索sql"));         eroot.addContent((new Element("order")).addContent("排序"));         Document doc=new Document(eroot);         XMLOutputter utputter = new XMLOutputter();         //如果不设置format,仅仅是没有缩进,xml还是utf-8的,因此format不是必要的         Format f = Format.getPrettyFormat();         //f.setEncoding("UTF-8");//default=UTF-8         outputter.setFormat(f);         outputter.output(doc, out);         out.close();     }    }

穿过紫堇,穿过木棉,穿过时影时现的悲喜和无常。

JDom输出UTF-8的XML完美解决方法

相关文章:

你感兴趣的文章:

标签云: