您的位置:首页 > 职场人生

黑马程序员-JAVA学习第7课-字符编码的操作

2011-05-24 00:49 369 查看
操作内容:
查看中文字符的GB2312码
查看中文字符的UTF-8码
查看中文字符的Unicode码
在Windows记事本中用不同编码格式存储文本文件
 
编程体验字符编码:
CharCode.java

public class CharCode {
 
 /**
  * Method main
  *
  *
  * @param args
  *
  */
 public static void main(String[] args) throws Exception {
  // TODO: 在这添加你的代码
  System.setProperty("file.encoding","GBK");
  System.getProperties().list(System.out);
  String strChina="中国";//JAVA中使用的是Unicode码
  for(int i=0;i<strChina.length();i++)
  {
   System.out.println(Integer.toHexString((int)strChina.charAt(i)));//取出每一个字符,转换成int就是字符的Unicode码
  }
  
  byte [] buf=strChina.getBytes();
    
  for(int i=0;i<buf.length;i++)
  {
   System.out.println(Integer.toHexString(buf[i]));
  }
  
  for(int i=0;i<buf.length;i++)
  {
   System.out.write(buf[i]);
   
  }
  System.out.println();
  System.out.println("中国");
 } 
}
 
 
 
CharDecode.java

public class CharDecode {
 
 /**
  * Method main
  *
  *
  * @param args
  *
  */
 public static void main(String[] args) throws Exception {
  // TODO: 在这添加你的代码
  System.getProperties().put("file.encoding","iso8859-1");
  System.out.println("please enter a chinese");
   
   byte buf[]=new byte[1024];
   int pos=0;
   String strInfo=null;
   
  while(true)
  {
   int ch=System.in.read();
   System.out.println(Integer.toHexString(ch));
   switch(ch)
   {
    case '/r':
     break;
    case '/n':
     strInfo=new String(buf,0,pos,"gb2312");
     for(int i=0;i<strInfo.length();i++)
     {
      System.out.println(Integer.toHexString(strInfo.charAt(i)));
     }
     break;
    default:
     buf[pos++]=(byte)ch;
   }
  }
 } 
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息