zoukankan      html  css  js  c++  java
  • dom4j处理中文之编码问题

    转自:http://zhonghuaweixu.blog.163.com/blog/static/11793205920106693820542/

     

    问题描述
     

    在使用dom4j的时候发现有时会出现这样一个问题:无法以UTF-8编码格式成功保存xml文件,具体表现为保存后中文呈现乱码(如果没有乱码,说明保存前的编码没有设置成功,保存成了本地的gbk或者gb2312格式)再次读取的时候会报类似如下的错误:

    Invalid byte 2 of 2-byte UTF-8 sequence. Nested exception: Invalid byte 2 of 2-byte UTF-8 sequence.

    Invalid byte 1 of 1-byte UTF-8 sequence. Nested exception: Invalid byte 1 of 1-byte UTF-8 sequence.

    Invalid byte 2 of 2-byte UTF-8 sequence. Nested exception: Invalid byte 2 of 2-byte UTF-8 sequence.

    Invalid byte 2 of 2-byte UTF-8 sequence. Nested exception: Invalid byte 2 of 2-byte UTF-8 sequence.

    Invalid byte 1 of 1-byte UTF-8 sequence. Nested exception: Invalid byte 1 of 1-byte UTF-8 sequence.

    2 字节 UTF-8 序列的无效字节 2。 Nested exception: 2 字节 UTF-8 序列的无效字

    在dom4j的范例中新建一个xml文档的代码如下:

    // 输出XML文档

    try

    {

        XMLWriter output = new XMLWriter(new FileWriter(new File("data/catalog.xml")));

        output.write(document);

        output.close();

    }

    catch (IOException e)

    {

        System.out.println(e.getMessage());

    }

    错误原因分析

    在上面的代码中输出使用的是FileWriter对象进行文件的输出。这就是不能正确进行文件编码的原因所在,Java中由Writer类继承下来的子类没有提供编码格式处理,所以dom4j也就无法对输出的文件进行正确的格式处理。这时候所保存的文件会以系统的默认编码对文件进行保存,在中文版的window下Java的默认的编码为GBK,也就是说虽然我们标识了要将xml保存为utf-8格式,但实际上文件是以GBK格式来保存的,所以这也就是为什么我们使用GBK、GB2312编码来生成xml文件能正确的被解析,而以UTF-8格式生成的文件不能被xml解析器所解析的原因。

    如何解决问题?

    首先我们看看dom4j是如何实现编码处理的,如下所示:
    publicXMLWriter(OutputStream out) throws UnsupportedEncodingException {

        //System.out.println("In OutputStream");

        this.format = DEFAULT_FORMAT;

        this.writer = createWriter(out, format.getEncoding());

        this.autoFlush = true;

       namespaceStack.push(Namespace.NO_NAMESPACE);

    }

    publicXMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException {

        //System.out.println("In OutputStream,OutputFormat");

        this.format = format;

        this.writer = createWriter(out, format.getEncoding());

        this.autoFlush = true;

       namespaceStack.push(Namespace.NO_NAMESPACE);

    }

    /**

    *GetanOutputStreamWriter,usepreferredencoding.

    */

    protected Writer createWriter(OutputStream outStream, String

        encoding) throws UnsupportedEncodingException {

        returnnew BufferedWriter(

            new OutputStreamWriter( outStream, encoding )

        );

    }

    由上面的代码我们可以看出dom4j对编码并没有进行什么很复杂的处理,完全通过 Java本身的功能来完成。所以我们在使用dom4j生成xml文件时不应该直接在构建XMLWriter时,为其赋一个Writer对象,而应该通过一个OutputStream的子类对象来构建。也就是说在我们上面的代码中,不应该用FileWriter对象来构建xml文档,而应该使用FileOutputStream对象来构建,修改后的代码如下:

    // 输出XML文档

    try

    {

        OutputFormat outFmt = new OutputFormat(" ", true);

        outFmt.setEncoding("UTF-8");

        XMLWriter output = new XMLWriter(new FileOutputStream(filename), outFmt);  

        output.write(document);

        output.close();

    }

    catch (IOException e)

    {

        System.out.println(e.getMessage());

    }

    如何读取呢?

    public List extractXMLText(File inputXml, String node)

    {

        List texts = null;

        try

        {

           // 使用SAXReader解析XML文档,SAXReader包含在org.dom4j.io包中。

           // inputXml是由xml文件创建的java.io.File。

           SAXReader saxReader = new SAXReader();

           saxReader.setEncoding("UTF-8");

           Document document = saxReader.read(inputXml);

              

           texts = document.selectNodes(node); // 获取sentence列表

        }

    catch (DocumentException e)

      {

           System.out.println(e.getMessage());

      }

      return texts;

    }

  • 相关阅读:
    算法训练 数位分离
    算法训练 薪水计算
    算法训练 整除问题
    算法训练 数对
    pom.xml一个简单配置
    MyBatis3.4.0以上的分页插件错误:Could not find method on interface org.apache.ibatis.executor.statement.StatementHandler named prepare. Cause: java.lang.NoSuchMethodException: org.apache.ibatis.executor.stateme
    MyBatis3-实现MyBatis分页
    mybatis 易百练习笔记
    maven pom.xml配置
    Description Resource Path Location Type The superclass "javax.servlet.http.HttpServlet" was not foun
  • 原文地址:https://www.cnblogs.com/honglihome/p/3440410.html
Copyright © 2011-2022 走看看