我正在编写一个 XML 解析器类,当我运行它时,有时它工作正常但有时它不起作用并抛出此异常:
MalformedByteSequenceException Invalid byte 1 of 1-byte UTF-8 sequence
谁能提供一些信息说明原因?
这是我的代码:
package TRT;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Gundem {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gundem gundem=new Gundem();
try {
URL url=new URL("http://www.trt.net.tr/rss/gundem.rss");
URLConnection connection=url.openConnection();
DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder=builderFactory.newDocumentBuilder();
Document document=docBuilder.parse(connection.getInputStream());
Element element=document.getDocumentElement();
Node node=(Node)element.getChildNodes();
System.out.println(node.getNodeName());
NodeList nodeList=node.getChildNodes();
Node channelNode=(Node)nodeList.item(0);
System.out.println(channelNode.getNodeName());
NodeList childNodeListOfChannelNode=channelNode.getChildNodes();
for(int i=0;i<childNodeListOfChannelNode.getLength();i++){
Node childNodesOfChannelNode=(Node)childNodeListOfChannelNode.item(i);
System.out.println(childNodesOfChannelNode.getNodeName());
if(childNodesOfChannelNode.getNodeName().equals(Constants.ITEM)){
Item item=new Item();
NodeList itemList=childNodesOfChannelNode.getChildNodes();
for(int j=0;j<itemList.getLength();j++){
Node childNodeOfItem=itemList.item(j);
if(childNodeOfItem.getNodeName().equals(Constants.TITLE)){
item.setTitle(childNodeOfItem.getTextContent());
System.out.println(item.getTitle());
System.out.println(gundem.dumpingInputAsHex(item.getTitle()));
}
else if(childNodeOfItem.getNodeName().equals(Constants.DESCRIPTION)){
item.setDescription(childNodeOfItem.getTextContent());
System.out.println(item.getDescription());
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0); // this line is for solving that problem; JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
}
public String dumpingInputAsHex(String input){
return String.format("%40x",new BigInteger(1,input.getBytes()));
}
}
最佳答案
最有可能的情况是,您正试图将使用其他字符集(例如 ISO-8859-1)编码的文档解析为 UTF-8。解析器遇到了一个 ISO-8859-1 字符,其值不允许在 UTF-8 中单独出现。
要解决此问题,您需要确定文档的实际 编码,然后根据 connection.getInputStream( )
,指定正确的编码。然后从阅读器创建一个 InputSource
并将 that 传递给 docBuilder.parse()
。
进一步研究:
我在 Eclipse (JDK 7) 中运行了您的代码,并且能够重现错误。然后,我在 Eclipse 中的两个 MalformedByteSequenceException
异常上设置异常断点,它没有失败。跟踪代码,我只能看到一次输入缓冲区中的无效字符。这向我表明 Xerces 解析器中某处存在竞争条件错误。
您可能需要向 Oracle 提交错误。
关于java - MalformedByteSequenceException 1 字节 UTF-8 序列的无效字节 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987535/