zoukankan      html  css  js  c++  java
  • String(byte[] bytes, Charset charset) 和 getBytes() 使用

    转自:https://techbirds.iteye.com/blog/1855960

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

  • 相关阅读:
    前端,DJ
    打印九九乘法表
    求数组中最大值和最小值
    求数组中最大值和次大值
    数据库 Mysql 使用,优化,索引
    List、Map、Set的区别与联系
    1001个整数,每个数范围1到1000,求出重复的数字。
    一个正整数是否等于因数之和
    滑动验证 和滑动图片验证JS
    cmd中mvn命令,出现No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
  • 原文地址:https://www.cnblogs.com/sharpest/p/10390028.html
Copyright © 2011-2022 走看看