现在的位置: 首页 > 综合 > 正文

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

2014年08月29日 ⁄ 综合 ⁄ 共 1464字 ⁄ 字号 评论关闭

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

测试代码:

    @Test  
    public void testBytes(){  
        //字节数  
        //中文:ISO:1 GBK:2 UTF-8:3     
        //数字或字母: ISO:1 GBK:1 UTF-8:1  
        String username = "中";  
        try {  
            //得到指定编码的字节数组    字符串--->字节数组  
            byte[] u_iso=username.getBytes("ISO8859-1");  
            byte[] u_gbk=username.getBytes("GBK");  
            byte[] u_utf8=username.getBytes("utf-8");  
            System.out.println(u_iso.length);  
            System.out.println(u_gbk.length);  
            System.out.println(u_utf8.length);  
            //跟上面刚好是逆向的,字节数组---->字符串  
            String un_iso=new String(u_iso, "ISO8859-1");  
            String un_gbk=new String(u_gbk, "GBK");  
            String un_utf8=new String(u_utf8, "utf-8");  
            System.out.println(un_iso);  
            System.out.println(un_gbk);  
            System.out.println(un_utf8);          
            //有时候必须是iso字符编码类型,那处理方式如下  
            String un_utf8_iso=new String(u_utf8, "ISO8859-1");       
            //将iso编码的字符串进行还原  
            String un_iso_utf8=new String(un_utf8_iso.getBytes("ISO8859-1"),"UTF-8");  
            System.out.println(un_iso_utf8);                  
              
        } catch (UnsupportedEncodingException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }

测试结果:

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")来得到正确的中文汉字"中".这样就既保证了遵守协议规定、也支持中文.


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

抱歉!评论已关闭.