java中使用string發生亂碼怎么解決?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
問題出在預發、生產和本地環境的系統編碼方式不一致,本地系統默認是UTF-8,而預發、生產環境默認是GBK編碼,因此導致出現亂碼。
如果不指定編碼方式,則默認以系統的編碼方式。
String csn = Charset.defaultCharset().name(); try { // use charset name decode() variant which provides caching. return decode(csn, ba, off, len); } catch (UnsupportedEncodingException x) { warnUnsupportedCharset(csn); } try { return decode("ISO-8859-1", ba, off, len); } catch (UnsupportedEncodingException x) { // If this code is hit during VM initialization, MessageUtils is // the only way we will be able to get any kind of error message. MessageUtils.err("ISO-8859-1 charset not available: " + x.toString()); // If we can not find ISO-8859-1 (a required encoding) then things // are seriously wrong with the installation. System.exit(1); return null; } System.getProperty("file.encoding") //查看系統默認編碼方式
解決方法如下:
1、使用string時進行轉碼
System.out.println(str); String str1 = new String(str.getBytes("ISO-8859-1"), "utf-8"); System.out.println(str1); String str2 = new String(str.getBytes("gb2312"), "utf-8"); System.out.println(str2); String str3 = new String(str.getBytes("gbk"), "utf-8"); System.out.println(str3);
2、將亂碼的字符串進行轉碼
String decodeStr=null; decodeStr = URLDecoder.decode(url, "utf-8");
因此在使用String的時候,無論 encode 或者 decode都要指定編碼方式,否則就和系統環境耦合了。
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創新互聯行業資訊頻道,感謝您對創新互聯的支持。
文章題目:java中使用string發生亂碼怎么解決-創新互聯
分享路徑:http://vcdvsql.cn/article0/djjooo.html
成都網站建設公司_創新互聯,為您提供手機網站建設、Google、搜索引擎優化、網站導航、營銷型網站建設、ChatGPT
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯