飛翔的起點

          從這里出發

          導航

          <2009年9月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          統計

          常用鏈接

          留言簿(5)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          byte數組和String之間的轉化

          JAVA里面關于byte數組和String之間的轉換問題

          把byte轉化成string,必須經過編碼。

          例如下面一個例子:

          import java.io.UnsupportedEncodingException;

          public class test{
           public static void main(String g[]) {
            String s = "12345abcd";
            byte b[] = s.getBytes();
            String t = b.toString();

            System.out.println(t);

           }
          }
          輸出字符串的結果和字符串s不一樣了.

          經過以下方式轉碼就可以正確轉換了:

          public class test{
           public static void main(String g[]) {
            String s = "12345abcd";
            byte b[] = s.getBytes();
            try {
             String t = new String(b);
             System.out.print(t);
            } catch (Exception e) {
             e.printStackTrace();
            }
           }
          }

          引用:
          String   str   =   "String"; 
                    byte[]   byte1   =   str.getBytes(); 
                    String   str1   =   new   String(byte1); 
                    byte[]   byte2   =   str1.getBytes(); 
                    String   str2   =   new   String(byte2); 
                    System.out.println("str<<<"   +   str); 
                    System.out.println("byte1<<<"   +   byte1); 
                    System.out.println("str1<<<"   +   str1); 
                    System.out.println("byte2<<<"   +   byte2); 
                    System.out.println("str2<<<"   +   str2); 
            ------------------------------------- 
            輸出結果 
            str<<<String 
            byte1<<<[B@192d342 
            str1<<<String 
            byte2<<<[B@6b97fd 
            str2<<<String 
            
            想請教為什么兩個byte輸出的不一樣呢? 
           

          String   str   =   "String"; 
                    byte[]   byte1   =   str.getBytes(); 
                    String   str1   =   new   String(byte1); 
                    byte[]   byte2   =   str1.getBytes(); 
            ---------- 
            注意byte1是str得到的byte數組,而byte2是另一個字符串str1得到的數組 
            他們本身也是兩個對象  
             
            直接打印實際上調用的是toString()方法,而toString()的默認實現是打印對象類型+hashCode()  
            [B表示byte數組  @表示之后的是地址  后面跟著的是hashCode,其實就是其虛擬機地址  
            

          posted on 2009-09-23 14:19 forgood 閱讀(3075) 評論(0)  編輯  收藏 所屬分類: java

          主站蜘蛛池模板: 林州市| 汝州市| 郁南县| 布拖县| 佳木斯市| 新竹县| 隆德县| 喀喇| 榆林市| 错那县| 理塘县| 隆昌县| 大丰市| 长治县| 平塘县| 阿拉善右旗| 岢岚县| 中方县| 四平市| 会同县| 新绛县| 石门县| 唐海县| 夏津县| 攀枝花市| 张掖市| 清苑县| 婺源县| 南乐县| 金塔县| 安塞县| 固原市| 米易县| 赤壁市| 新密市| 通辽市| 雅江县| 安溪县| 闽侯县| 于田县| 林州市|