java中使用string發(fā)生亂碼怎么解決?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
問題出在預(yù)發(fā)、生產(chǎn)和本地環(huán)境的系統(tǒng)編碼方式不一致,本地系統(tǒng)默認(rèn)是UTF-8,而預(yù)發(fā)、生產(chǎn)環(huán)境默認(rèn)是GBK編碼,因此導(dǎo)致出現(xiàn)亂碼。
如果不指定編碼方式,則默認(rèn)以系統(tǒng)的編碼方式。
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") //查看系統(tǒng)默認(rèn)編碼方式
解決方法如下:
1、使用string時(shí)進(jìn)行轉(zhuǎn)碼
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、將亂碼的字符串進(jìn)行轉(zhuǎn)碼
String decodeStr=null; decodeStr = URLDecoder.decode(url, "utf-8");
因此在使用String的時(shí)候,無論 encode 或者 decode都要指定編碼方式,否則就和系統(tǒng)環(huán)境耦合了。
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。