日期:2014-05-16  浏览次数:20397 次

MalformedByteSequenceException: Invalid byte 2 of 3-byte UTF-8 sequence

代码行:

String content=new String(getBytesFromFile(new File("monitor_config.xml")));
		Document doc = null;
		SAXBuilder saxBuilder = new SAXBuilder();
		
		try {
			doc = saxBuilder.build(new ByteArrayInputStream(content.getBytes()));
		} catch (JDOMException e) {
			throw new SettingsException("monitor配置读取时出现xml解析异常", e);
		} catch (IOException e2) {
			throw new SettingsException("monitor配置读取时出现I/O异常", e2);
		}

?

stack trace:

Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 3-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.scanLiteral(Unknown Source)
?at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanAttributeValue(Unknown Source)
?at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanAttribute(Unknown Source)
?at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(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.XMLNSDocumentScannerImpl.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.AbstractSAXParser.parse(Unknown Source)
?at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
?at org.jdom.input.SAXBuilder.build(SAXBuilder.java:453)
?at org.jdom.input.SAXBuilder.build(SAXBuilder.java:770)
?at com.metarnet.adapter.ecm.monitor.setting.impl.MonitorSettings.read(MonitorSettings.java:46)
?... 5 more

?

解决方法:首先确定要读取文件的编码格式为UTF-8,

??????????????? 然后将

saxBuilder.build(new ByteArrayInputStream(content.getBytes()));

?改为:

?????????????????

  saxBuilder.build(new ByteArrayInputStream(content.getBytes("UTF-8")));

?