今天在編碼的時候遇到如下問題
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;
}
實作的功能将一個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>";
調用
String2InputStream(ExpXmlText );
結果報:
經查時由于聲明的ExpXmlText 是UTF-8編碼的,而轉換的時候使用預設的編碼是gbk的
查明原因後,将原函數修訂如下
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes("utf-8"));
問題解決
本文轉自elbertchen 51CTO部落格,原文連結:http://blog.51cto.com/linkyou/283238,如需轉載請自行聯系原作者