java 字符串编码转换 字符集/编码的见解

15 篇文章 0 订阅
14 篇文章 0 订阅

转http://www.cnblogs.com/kenkofox/archive/2010/04/23/1719009.html



!!!Java要转换字符编码:就一个String.getBytes("charsetName")解决,返回的字节数组已经是新编码的了~~至于后边是new String组装还是网络发送,就再处理了。  

 

复制代码
    
    
1 try { 2 String test = " " ; 3 System.out.println(System.getProperty( " file.encoding " )); // java默认编码是UTF-8 4   System.out.println(test);
        //getBytes已经是转码操作,不填的就默认用系统规定的 5 System.out.println( new String(test.getBytes(), " GB2312 " )); 6   System.out.println( new String(test.getBytes( " GB2312 " ), " GB2312 " )); // 用什么拆就用什么组装,否则显示乱码 7   } catch (UnsupportedEncodingException ex) { 8 Logger.getLogger(Main. class .getName()).log(Level.SEVERE, null , ex); 9 }
复制代码

 

 

输出结果:

UTF-8

涓�

 

System.out.println(test.getBytes("GB2312").length);
System.out.println(test.getBytes("UTF8").length);
System.out.println(test.getBytes("GBK").length);

分别输出2,3,2,同样是“一”,用不同编码拆成字节数组就占不同的位数。GBK,GB2312都两字节编码。

 

2010年10月15日新加以下内容:

 

复制代码
   
   
// 本程序默认在UTF8编码下运行 String a = " 郑高强 " ; String b = null ; b = new String(a.getBytes(), " UTF8 " ); System.out.println(b); // 正确显示 b = new String(a.getBytes( " GB2312 " ), " GB2312 " ); System.out.println(b); // 正确显示。虽然a本来默认是三字节编码的,但getBytes("GB2312") // 把整个字节数组按双字节形式转换了一次。用GB2312来解释这个新字节数组就对了 b = new String(a.getBytes( " GB2312 " ), " UTF8 " ); System.out.println(b); // 乱码。已经转为双字节,还用UTF8解释就错了。 // 还没想到怎么把b救回来。好像没办法使得b重新正确显示了。 b = new String(a.getBytes(), " GB2312 " ); System.out.println(b); // 乱码。getBytes已经把字符串逐个字符按UTF8格式,拆散为N个字节。 // 后边硬用GB2312来解释这N个字节,肯定乱码。UTF8三字节,GB2312双字节 b = new String(a.getBytes( " UTF8 " ), " GB2312 " ); // 同上一句其实一样 System.out.println(b); // 乱码
复制代码

 

结果:

郑高强
郑高强
֣��ǿ
���寮�
���寮�

 

字符编码转换关键是要理解内在的机理。。。编码的关键是要理解最底层那个字节数组是怎么编码的,例如GB2312用两个字节表示一个汉字,UTF8用三个字节表示一个汉字,可见,底层的字节数组肯定有不同~~~

 

!!!Java要转换字符编码:就一个String.getBytes("charsetName")解决,这时候已经把原来String的字节数组逐个字符的转化了,此时编码已经变了。例如原来是UTF8三字节编码,转为GB2312,已经变成双字节编码了,这个byte数组已经比原来String内含的数组要短。

而new String只是一个组装String的过程,传入的字节数组是什么编码的,就该用什么编码组装(或者叫解释),不然就悲剧了~~~

 

!!!虽然程序默认编码是UTF8,这不代表程序中用GB2312编码的字符串就无法正确显示。(这是我个人之前的误解)因为out.println的时候,系统会自动处理。其实默认编码是UTF8,就只是指getBytes或者new InputStreamReader这样的操作的时候,默认用UTF8来解释。


 

再说说编码和字符集的关系:详细见另外一个文章http://www.cnblogs.com/kenkofox/archive/2010/10/15/1851962.html

 

最后贴出JDK对String的getBytes和new String(byte[], charsetName)的解释:

public byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

 

new String(byte[], charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.


kenkofox@qq.com




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值