Java判断字符串编码格式并转码

 public static String getEncoding(String str) {
        String encodes[]={"GB2312","ISO-8859-1","UTF-8","GBK"};
        for(String encode :encodes){
            try {
                if (str.equals(new String(str.getBytes(encode), encode))) {
                    return encode;
                }
            } catch (Exception exception) {
            }
        }
        return "";
  }

然后再调用

String str="...."

String res= new String (str.getBytes(getEncoding(str)),"UTF-8");

即可转换为需要的编码格式的字符串

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×