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);
str.getbytes(charsetname);charsetname是原本字符的编码
"utf-8"是将str转换为utf-8编码。
new string(str.getbytes(“gbk”),“iso8859-1”)时
第一步:byte[] bytes=str.getbytes(“gbk”)
告诉java虚拟机将中文以“gbk”的方式转换为字节数组。一个汉字对应两个字节。
对应的第二步便是:
string s=new string(bytes,“iso8859-1”)时,此时是将每1字节组装成一个“?” 。此时的s是若干个“?”,我们可以把“?”看做是一种特殊的汉字,它代表的信息并没有损失是可以还原回来的。
java.lang.string.getbytes(string charsetname) 方法编码将此string使用指定的字符集的字节序列,并将结果存储到一个新的字节数组。
声明
以下是java.lang.string.getbytes()方法的声明
public byte[] getbytes(string charsetname) throws unsupportedencodingexception
参数:charset -- 这是一个支持的字符集的名称。
返回值:此方法返回得到的字节数组。
new string(byte[],decode)方法
与getbytes相对的,可以通过new string(byte[], decode)的方式来还原这个中字,
这个new string(byte[],decode)实际是使用指定的编码decode来将byte[]解析成字符串.
异常:unsupportedencodingexception -- 如果不支持指定的字符集。
更多java知识请关注java基础教程栏目。
以上就是java中string乱码解决方法介绍的详细内容。
