org.xml.sax.SAXParseException: Invalid byte 2 of 2-byte UTF-8 sequence。解析xml,出现该异常。
SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(new File(responseXmlPath)); Element foo = doc.getRootElement();
在生成Document 对象时,Eclipse编译文件的编码或者文件所在地的编码和该文件需要的编码不一致,会产生该异常。 解决办法:在生成该文件或者向文件中写入文件时,指定为所需编码。如:
BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(new File(responseXmlPath)), "UTF-8")); bw.write(resultStr); bw.flush(); } catch (UnsupportedEncodingException e) { logger.error("when create OutputStreamWriter, encoding error", e); } catch (IOException e) { logger.error("when write resultStr to responseXml error:", e); } finally { if (bw != null) try { bw.close(); } catch (IOException e) { logger.error( "when finally close the BufferedWriter error:", e); } }
最好在获取Documen的时候,也用指定编码的IO获取。
Document doc = builder.build(new InputStreamReader( new FileInputStream(new File(responseXmlPath)), "UTF-8"));
但是生成文件时,必须指定为所需编码。