在使用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也就無法對輸出的文件進行正確的格式處理。這時候所保存的文件會以系統的默認編碼對文件進行保存,在中文版的window下Java的默認的編碼為GBK,也就是說雖然我們標識了要將xml保存為utf-8格式,但實際上文件是以GBK格式來保存的,所以這也就是為什么我們使用GBK、GB2312編碼來生成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 閱讀(235)
評論(0) 編輯 收藏