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

来源:互联网 发布:ubuntu中安装超级终端 编辑:程序博客网 时间:2024/05/01 21:33

操作内容:

查看中文字符的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;
   }
  }
 } 
}