Java com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException:4字节UTF-8序列(XML)的字节2无效

Java com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException:4字节UTF-8序列(XML)的字节2无效,java,xml,dom,encoding,utf-8,Java,Xml,Dom,Encoding,Utf 8,我得到了这个例外,问题是因为我输入了utf-8编码的字符 在我的XML文件的顶部是: 我添加了编码。但我还是有例外 //Set the format Format format = Format.getPrettyFormat(); format.setEncoding("UTF-8"); XMLOutputter xmlOutput = new XMLOutputter(format); // Create a new file and write XML t

我得到了这个例外,问题是因为我输入了utf-8编码的字符

在我的XML文件的顶部是:
我添加了编码。但我还是有例外

 //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)

如何解决这个问题?

您告诉解析器文件是用UTF-8编码的,而解析器告诉您不是。我倾向于相信解析器

有两种诊断方法:

(a) 在二进制级别检查文件,查看实际的八位字节是什么,以及实际的编码是什么


(b) 研究文件是如何产生的,以及编码字符可能有多糟糕。

我也有同样的问题。我的问题是,我用jdom和FileWriter(xmlFile)创建了一个新的XML文件。FileWriter无法创建UTF-8文件。
相反,使用文件输出流(xmlFile)解决了这个问题。

Post您的xml文件,我尝试从记事本插入utf-8数据,效果很好。但是,当我从java应用程序中执行此操作时,我遇到了这个错误。所以错误不在文件中。好吧,我所能做的就是说错误似乎不在你给我们看的代码中。这稍微减少了你必须去看的地方。