字符编码工具类

来源:互联网 发布:山东网络诈骗案 编辑:程序博客网 时间:2024/06/10 01:18
/**
   * 转换编码 ISO-8859-1到GB2312
   * @param text
   * @return
   */
  public static final String ISO2GB(String text) {
    String result = "";
    try {
      result = new String(text.getBytes("ISO-8859-1"), "GB2312");
    }
    catch (UnsupportedEncodingException ex) {
      ex.printStackTrace();
    }
    return result;

  }


 /**
   * Utf8URL编码
   * @param s
   * @return
   */
  public static final String Utf8URLencode(String text) {
    StringBuffer result = new StringBuffer();

    for (int i = 0; i < text.length(); i++) {

      char c = text.charAt(i);
      if (c >= 0 && c <= 255) {
        result.append(c);
      }else {

        byte[] b = new byte[0];
        try {
          b = Character.toString(c).getBytes("UTF-8");
        }catch (Exception ex) {
        }

        for (int j = 0; j < b.length; j++) {
          int k = b[j];
          if (k < 0) k += 256;
          result.append("%" + Integer.toHexString(k).toUpperCase());
        }

      }
    }

    return result.toString();
  }


0 0
原创粉丝点击