二级Java中的字符编码与解码
来源:优易学  2011-11-2 15:35:07   【优易学:中国教育考试门户网】   资料下载   IT书店

 

  //--以字符流的方式读取windows记事本创建的有文件编码标志的UTF-8文件时错误
   br = new BufferedReader(new InputStreamReader(new FileInputStream(
    "e:/utf-8-2.txt"), "UTF-8"));
   System.out.println(br.readLine());//?中a
   br.close();

   //--以字节流读取有编码标志的UTF-8文件
   FileInputStream fi = new FileInputStream("e:/utf-8-2.txt");
   byte[] b = new byte[1024];
   int readCount = fi.read(b);
   //手动丢弃前三个字节的内容
   System.out.println(new String(b, 3, readCount - 3, "UTF-8"));//中a
   fi.close();
   } catch (UnsupportedEncodingException e) {

   e.printStackTrace();
   } catch (FileNotFoundException e) {
   e.printStackTrace();
   } catch (IOException e) {
   e.printStackTrace();
   }
  }

  /**
   * 英文字符以GBK编码时只占一个字节,且与Unicode编码兼容,中文字符以GBK编码时,占
   * 两个字节。
   * GBK对中文编码时,每个字节的最高位都是一
   */
  public void testCharToGBK() {
   try {
   //--中文字符转GBK
   byte[] encodeArr = String.valueOf(chineseChar).getBytes("GBK");
   //十进制编码输出
   for (int i = 0; i < encodeArr.length; i++) {
    //-42 -48
    System.out.print(encodeArr[i] + " ");
   }
   System.out.println();
   //十六进制编码输出
   for (int i = 0; i < encodeArr.length; i++) {
    //D6 D0
    System.out.print(byteToHex(encodeArr[i]) + " ");
   }
   System.out.println();
   //所占字节数
   System.out.println(encodeArr.length);//2
   //--英文字符转GBK
   encodeArr = String.valueOf(englishChar).getBytes("GBK");
   //十进制编码输出
   for (int i = 0; i < encodeArr.length; i++) {
    //97
    System.out.print(encodeArr[i] + " ");
   }
   System.out.println();
   //十六进制编码输出
   for (int i = 0; i < encodeArr.length; i++) {
    //61
    System.out.print(byteToHex(encodeArr[i]) + " ");
   }
   System.out.println();
   //所占字节数
   System.out.println(encodeArr.length);//1

   } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
   }
  }

  public void testCharFromUTF16() {
   try {
   byte[] encodeArr = String.valueOf(chineseChar).getBytes("UTF-16");
   System.out.println(new String(encodeArr, "UTF-16"));//中

   encodeArr = new byte[] { -0x2, -0x1, 0x4E, 0x2D };
   System.out.println(new String(encodeArr, "UTF-16"));//中
   } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
   }
  }

  public static String byteToHex(byte b) {
   return Integer.toHexString((b & 0x000000FF) | 0xFFFFFF00).substring(6)
    .toUpperCase();
  }
  }

上一页  [1] [2] [3] [4] 

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训