2014-02-21 40 views
2

我得到這個Exceptoin,問題是因爲我輸入的字符是utf-8編碼。com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException:4字節UTF-8序列(XML)的無效字節2

在我的XML文件的頂部是說:<?xml version="1.0" encoding="UTF-8" ?> 而且我已經添加了編碼。但是,我得到這個例外。

//Set the format 
    Format format = Format.getPrettyFormat(); 
    format.setEncoding("UTF-8"); 
    XMLOutputter xmlOutput = new XMLOutputter(format); 
    // Create a new file and write XML to it 
    xmlOutput.output(doc, new FileOutputStream(new File(XMLEditorService 
      .getXMLEditorService().getFile()))); 

的錯誤似乎當我解析該文件中出現:

Document xmlDocument = builder.parse(file); 

com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 4-byte UTF-8 sequence. 
    at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(Unknown Source) 
    at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(Unknown Source) 
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(Unknown Source) 
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.peekChar(Unknown Source) 
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source) 
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) 
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) 
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) 
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) 
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) 
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) 
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) 
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source) 

如何解決這個問題?

+0

發佈您的xml文件也 – Naren

回答

1

您正在告訴解析器文件使用UTF-8編碼,解析器告訴您它不是。我傾向於相信解析器。

有兩種方法來診斷:

(一)檢查在二進制級別的文件,看看實際的字節是什麼,以及實際的編碼。 (b)研究該文件是如何產生的,以及如何編碼嚴重的字符可能會出現在那裏。

+0

我試圖從記事本插入utf-8數據,它工作正常。但是當我從我的Java應用程序執行它時,我得到了這個錯誤。所以錯誤不在文件中。 – Sembrano

+0

那麼,我所能做的就是說這個錯誤似乎沒有出現在你向我們展示的代碼中。這略微減少了你必須看的地方。 –

1

我也有同樣的問題。我的問題是,我創建了一個新的XML文件與jdom和FileWriter(xmlFile)。 FileWriter無法創建UTF-8文件。 而是使用FileOutputStream(xmlFile)解決了它。

相關問題