在使用dom4j的时候发现有时会出现这样一个问题:无法以UTF-8编码格式成功保存xml文件
错误信息:
Invalid byte 1 of 1-byte UTF-8 sequence. Nested exception: Invalid byte 1 of 1-byte UTF-8 sequence.
。。。
代码:
private void saveDocumentToFile() {
        
try {
            OutputFormat format 
= OutputFormat.createPrettyPrint();
            format.setEncoding(
"UTF-8");
            XMLWriter writer 
= new XMLWriter(new FileWriter(xmlFile), format);

            writer.write(document);
            writer.close();
        } 
catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

dom4j的编码处理:
public XMLWriter(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);

}

public XMLWriter(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);

}

/**

* Get an OutputStreamWriter, use preferred encoding.

*/

protected Writer createWriter(OutputStream outStream, String

    encoding) 
throws UnsupportedEncodingException {

    
return new BufferedWriter(

        
new OutputStreamWriter( outStream, encoding )

    );

}

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

修改代码:
private void saveDocumentToFile() {
        
try {
            OutputFormat format 
= OutputFormat.createPrettyPrint();
            format.setEncoding(
"UTF-8");
            XMLWriter writer 
= new XMLWriter(new FileOutputStream(xmlFile), format);

            writer.write(document);
            writer.close();
        } 
catch (Exception ex) {
            ex.printStackTrace();
        }
    }











posted on 2010-11-05 11:24 Ying-er 阅读(225) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: