问题出在预发、生产和本地环境的系统编码方式不一致,本地系统默认是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入门教程,欢迎在线学习!
以上就是java string乱码的详细内容。
