当前位置: 代码迷 >> Web前端 >> 对字符串存在中文字符开展转码成UTF-8
  详细解决方案

对字符串存在中文字符开展转码成UTF-8

热度:100   发布时间:2012-09-14 11:53:44.0
对字符串存在中文字符进行转码成UTF-8
对应方法如:
public static String toUtf8String(String str,String codeType) {   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i < str.length(); i++) {   
                char c = str.charAt(i);   
                if (c >= 0 && c <= 255) {   
                        sb.append(c);   
                } else {   
                        byte[] b;   
                        try {   
                                b = String.valueOf(c).getBytes(codeType);   
                        } catch (Exception ex) {   
                               // System.out.println(ex);   
                                b = new byte[0];   
                        }   
                        for (int j = 0; j < b.length; j++) {   
                                int k = b[j];   
                                if (k < 0)   
                                        k += 256;   
                                sb.append("%" + Integer.toHexString(k).toUpperCase());   
                        }   
                }   
        }   
        return sb.toString();   
   }
  相关解决方案