String(byte[] bytes, Charset charset) 和 getBytes() 使用

来源:互联网 发布:淘宝店铺文案 编辑:程序博客网 时间:2024/04/29 13:27
 

参考这篇文章:http://blog.csdn.net/maxracer/article/details/6075057

测试代码:

[java] view plain copy
 print?
  1. @Test  
  2.     public void testBytes(){  
  3.         //字节数  
  4.         //中文:ISO:1 GBK:2 UTF-8:3     
  5.         //数字或字母: ISO:1 GBK:1 UTF-8:1  
  6.         String username = "中";  
  7.         try {  
  8.             //得到指定编码的字节数组    字符串--->字节数组  
  9.             byte[] u_iso=username.getBytes("ISO8859-1");  
  10.             byte[] u_gbk=username.getBytes("GBK");  
  11.             byte[] u_utf8=username.getBytes("utf-8");  
  12.             System.out.println(u_iso.length);  
  13.             System.out.println(u_gbk.length);  
  14.             System.out.println(u_utf8.length);  
  15.             //跟上面刚好是逆向的,字节数组---->字符串  
  16.             String un_iso=new String(u_iso, "ISO8859-1");  
  17.             String un_gbk=new String(u_gbk, "GBK");  
  18.             String un_utf8=new String(u_utf8, "utf-8");  
  19.             System.out.println(un_iso);  
  20.             System.out.println(un_gbk);  
  21.             System.out.println(un_utf8);          
  22.             //有时候必须是iso字符编码类型,那处理方式如下  
  23.             String un_utf8_iso=new String(u_utf8, "ISO8859-1");       
  24.             //将iso编码的字符串进行还原  
  25.             String un_iso_utf8=new String(un_utf8_iso.getBytes("ISO8859-1"),"UTF-8");  
  26.             System.out.println(un_iso_utf8);                  
  27.               
  28.         } catch (UnsupportedEncodingException e) {  
  29.             // TODO Auto-generated catch block  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  

测试结果:

1
 2
 3
 ?
 中
 中
 ä¸­
 中

从转载的文章摘:

乱码原因:为什么使用ISO8859-1编码再组合之后,无法还原"中"字呢,其实原因很简单,因为ISO8859-1编码的编码表中,根本就没有包含汉字字符,当然也就无法通过"中".getBytes("ISO8859-1");来得到正确的"中"字在ISO8859-1中的编码值了,所以再通过new String()来还原就无从谈起了.

有时候,为了让中文字符适应某些特殊要求(如http header头要求其内容必须为iso8859-1编码),可能会通过将中文字符按照字节方式来编码的情况,如:
String s_iso88591 = new String("中".getBytes("UTF-8"),"ISO8859-1"),这样得到的s_iso8859-1字符串实际是三个在ISO8859-1中的字符,在将这些字符传递到目的地后,目的地程序再通过相反的方式String s_utf8 = new String(s_iso88591.getBytes("ISO8859-1"),"UTF-8")来得到正确的中文汉字"中".这样就既保证了遵守协议规定、也支持中文.


1 0