编码问题,java,当不知道自己的字符串编码是什么的时候,可以用如下程序进行尝试并自动转码utf-8,源码直接可用

/**
* 编码变为utf-8
*/
public static String encode2utf8(String str) {    
        String encode = "GB2312";    
       try {    
           if (str.equals(new String(str.getBytes(encode), encode))) {    
                String s = encode;
                System.out.println(encode);
               return new String(str.getBytes(encode), "utf-8");    
            }    
        } catch (Exception exception) {    
        }    
        encode = "ISO-8859-1";    
       try {    
           if (str.equals(new String(str.getBytes(encode), encode))) {    
                String s1 = encode;   
                System.out.println(encode);
               return new String(str.getBytes(encode), "utf-8");   
            }    
        } catch (Exception exception1) {    
        }    
        encode = "UTF-8";    
       try {    
           if (str.equals(new String(str.getBytes(encode), encode))) {    
                String s2 = encode; 
                System.out.println(encode);
               return new String(str.getBytes(encode), "utf-8");    
            }    
        } catch (Exception exception2) {    
        }    
        encode = "GBK";    
       try {    
           if (str.equals(new String(str.getBytes(encode), encode))) {    
                String s3 = encode; 
                System.out.println(encode);
               return new String(str.getBytes(encode), "utf-8");    
            }    
        } catch (Exception exception3) {    
        }    
       return "";    
    }

猜你喜欢

转载自blog.csdn.net/u013294097/article/details/80299423