今天在编码的时候遇到如下问题
java.io.UTFDataFormatException: Invalid byte 2 of 2-byte UTF-8 sequence.
函数源码:
static InputStream String2InputStream(String str) throws Exception{
ByteArrayInputStream stream = new ByteArrayInputStream()
return stream;
}
ByteArrayInputStream stream = new ByteArrayInputStream()
return stream;
}
实现的功能将一个xml字符串转换为Stream类型。
调用时的源码
String ExpXmlText ="<?xml version=\"1.0\" encoding=\"utf-8\"?><AppSubscResult>" +
" <appId>elbert_app_dsc005</appId>" +
" <longId>wangwang101112347</longId>" +
" <time>1236235618357</time>" +
" <sign>a2e82a649b38ad10790160ec40e282af</sign>" +
" <result>Yes</result>" +
" <subscUserId>elb_aui_005</subscUserId>" +
" <appInstanceId>USER8B38B4C13EFE7276F75889E3123C4428</appInstanceId>" +
" <gmtStart>"+util.TimeHelp.getTimestamp_BeforeNDay(65)+" 00:00:00</gmtStart>" +
" <gmtEnd>"+util.TimeHelp.getTimestamp_BeforeNDay(7)+" 23:59:59</gmtEnd>" +
" <subscUrl>http://mall.alisoft.com/apps/subsc/subscDisplay!execute.jspa?appId=elbert_app_dsc005</subscUrl>" +
" <errorMessage>" +
"</errorMessage>" +
"</AppSubscResult>";
" <appId>elbert_app_dsc005</appId>" +
" <longId>wangwang101112347</longId>" +
" <time>1236235618357</time>" +
" <sign>a2e82a649b38ad10790160ec40e282af</sign>" +
" <result>Yes</result>" +
" <subscUserId>elb_aui_005</subscUserId>" +
" <appInstanceId>USER8B38B4C13EFE7276F75889E3123C4428</appInstanceId>" +
" <gmtStart>"+util.TimeHelp.getTimestamp_BeforeNDay(65)+" 00:00:00</gmtStart>" +
" <gmtEnd>"+util.TimeHelp.getTimestamp_BeforeNDay(7)+" 23:59:59</gmtEnd>" +
" <subscUrl>http://mall.alisoft.com/apps/subsc/subscDisplay!execute.jspa?appId=elbert_app_dsc005</subscUrl>" +
" <errorMessage>" +
"</errorMessage>" +
"</AppSubscResult>";
调用
String2InputStream(ExpXmlText );
结果报:
java.io.UTFDataFormatException: Invalid byte 2 of 2-byte UTF-8 sequence.
经查时由于声明的ExpXmlText 是UTF-8编码的,而转换的时候使用默认的编码是gbk的
查明原因后,将原函数修订如下
static InputStream String2InputStream(String str) throws Exception{
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes("utf-8"));
return stream;
}
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes("utf-8"));
return stream;
}
问题解决
本文转自elbertchen 51CTO博客,原文链接:http://blog.51cto.com/linkyou/283238,如需转载请自行联系原作者