黑马程序员:字符的编码和解码(输入中文查看他的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();
        }
      }
  
  
 }

}

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