黑馬程序員:字符的編碼和解碼(輸入中文查看他的Unicode碼)

import com.sun.corba.se.impl.oa.toa.TOA;


public class CharDeCode {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //System.getProperties().list(System.out);
     System.setProperty("file.encoding","iso8859-1");
 System.out.print("please enter a chinese String:");
  int ch=0;
  byte[] buf=new byte[1024];
  int  pos=0;
  String str =null;
    while(true)
   {
     try
     {
          ch=System.in.read();
          System.out.println(Integer.toHexString(ch));
          switch(ch)
          {
             case '/r':           
              break;
             case '/n':
               str=new String(buf,0,pos,"gb2312"); //switch 裏不能定義變量
                 /*gb2312 可不寫 因爲我們的缺省字符集 就是GB2312*/
               for(int i=0;i<str.length();i++)
               {
                System.out.println(Integer.toHexString(
                  str.charAt(i)));
             /*如果我們得到一個GB2312卻被iso8859-1解碼的String
              * 我們可以將它編碼還原爲字節數組,在解碼成GB2312 如下:       
              *System.out.print(new String((str.getBytes
              *    ("iso8859-1")),"gb2312"));
              */
                 }
                 break;
             default:
              buf[pos++]=(byte)ch;
          }
         
     }catch(Exception e)
        {
       e.printStackTrace();
        }
      }
  
  
 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章