A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© ℃葫芦 中级黑马   /  2015-8-17 21:58  /  183 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class EncodeDemo {

  2.         /**
  3.          * @param args
  4.          * @throws IOException
  5.          */
  6.         public static void main(String[] args) throws IOException {

  7.                 /*
  8.                  * 字符串 --> 字节数组:编码。
  9.                  * 字节数组 --> 字符串:解码。
  10.                  *
  11.                  * 你好:GBK:  -60 -29 -70 -61
  12.                  *
  13.                  * 你好: utf-8: -28 -67 -96 -27 -91 -67
  14.                  *
  15.                  *
  16.                  * 如果你编错了,解不出来。
  17.                  * 如果编对了,解错了,有可能有救。
  18.                  */
  19.                
  20.                 String str = "谢谢";
  21.                
  22.                 byte[] buf = str.getBytes("gbk");
  23.                
  24.                 String s1 = new String(buf,"UTF-8");
  25.                
  26.                 System.out.println("s1="+s1);
  27.                
  28.                
  29.                 byte[] buf2 = s1.getBytes("UTF-8");//获取源字节.
  30.                
  31.                 printBytes(buf2);//-17 -65 -67 -17 -65 -67 -17 -65 -67
  32.                                         //-17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67
  33.                                         //-48 -69 -48 -69
  34.                 String s2 = new String(buf2,"GBK");
  35.                
  36.                 System.out.println("s2="+s2);
  37.                
  38.                
  39. //                encodeDemo(str);
  40.                
  41.                
  42.                
  43.         }

  44.         /**
  45.          * @param str
  46.          * @throws UnsupportedEncodingException
  47.          */
  48.         public static void encodeDemo(String str)
  49.                         throws UnsupportedEncodingException {
  50.                 //编码;
  51.                 byte[] buf = str.getBytes("UTF-8");
  52.                
  53. //                printBytes(buf);
  54.                
  55.                 //解码:
  56.                 String s1 = new String(buf,"UTF-8");
  57.                
  58.                 System.out.println("s1="+s1);
  59.         }

  60.         private static void printBytes(byte[] buf) {
  61.                 for(byte b : buf){
  62.                         System.out.print(b +" ");
  63.                 }
  64.         }

  65. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马