判断String字符串的常用字符编码集(UTF-8,gb2321,iso-8895-1,GBK)的工具类

    /**
     * 判断字符串的编码
     * @param str
     * @return
     */
    public static String getEncoding(String str){
        String encode = "GB2312";
        try{
            if(str.equals(new String(str.getBytes(encode),encode))){
                String s = encode;
                return s;
            }
        }catch(Exception exception){
        }
        encode = "ISO-8859-1";
        try{
            if(str.equals(new String(str.getBytes(encode),encode))){
                String s1 = encode;
                return s1;
            }
        }catch(Exception exception1){
        }
        encode = "UTF-8";
        try{
            if(str.equals(new String(str.getBytes(encode),encode))){
                String s2 = encode;
                return s2;
            }
        }catch(Exception exception2){
        }
        encode = "GBK";
        try{
            if(str.equals(new String(str.getBytes(encode),encode))){
                String s3 = encode;
                return s3;
            }
        }catch(Exception exception3){
        }
        return "";
    }

ps:使用时可直接通过返回的编码集进行读取并转码

   }
            //获得字符集
            String encode = SFTPUtil.getEncoding(request.getParameter("name"));
            //根据不同的编码集动态转码成utf-8
              String fileName= new String(request.getParameter("name").getBytes(encode),"UTF-8");
   
发布了88 篇原创文章 · 获赞 5 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42410730/article/details/90750224