問題描述
在使用dom4j的時候發(fā)現(xiàn)有時會出現(xiàn)這樣一個問題:無法以UTF-8編碼格式成功保存xml文件,具體表現(xiàn)為保存后中文呈現(xiàn)亂碼(如果沒有亂碼,說明保存前的編碼沒有設置成功,保存成了本地的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.
在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也就無法對輸出的文件進行正確的格式處理。這時候所保存的文件會以系統(tǒng)的默認編碼對文件進行保存,在中文版的window下Java的默認的編碼為GBK,也就是說雖然我們標識了要將xml保存為utf-8格式,但實際上文件是以GBK格式來保存的,所以這也就是為什么我們使用GBK、GB2312編碼來生成xml文件能正確的被解析,而以UTF-8格式生成的文件不能被xml解析器所解析的原因。
如何解決問題?
首先我們看看dom4j是如何實現(xiàn)編碼處理的,如下所示:
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 )
);
}
由上面的代碼我們可以看出dom4j對編碼并沒有進行什么很復雜的處理,完全通過 Java本身的功能來完成。所以我們在使用dom4j生成xml文件時不應該直接在構建XMLWriter時,為其賦一個Writer對象,而應該通過一個OutputStream的子類對象來構建。也就是說在我們上面的代碼中,不應該用FileWriter對象來構建xml文檔,而應該使用 FileOutputStream對象來構建,修改后的代碼如下:
// 輸出XML文檔
try
{
OutputFormat outFmt = new OutputFormat("\t", 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文件創(chuàng)建的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;
}