Java 获取 字符串编码格式

判断一个字符串的编码格式:

   public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (isEncoding(str, encode)) { // 判断是不是GB2312
                return encode;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (isEncoding(str, encode)) { // 判断是不是ISO-8859-1
                return encode;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (isEncoding(str, encode)) { // 判断是不是UTF-8
                return encode;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (isEncoding(str, encode)) { // 判断是不是GBK
                return encode;
            }
        } catch (Exception exception3) {
        }
        return "如果都不是,说明输入的内容不属于常见的编码格式"; // 如果都不是,说明输入的内容不属于常见的编码格式。
    }

    public static boolean isEncoding(String str, String encode) {
        try {
            if (str.equals(new String(str.getBytes(), encode))) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("!!!!!!  isEncoding" + e.getMessage());
        }
        return false;
    }

调用方法:

String str=getEncoding(strMsg);
logger.error("!!!!!!!!!!!!!!!!!!! " +str  +"  !!!!!!!  "+strMsg);

感谢:

https://blog.csdn.net/qq_26230421/article/details/89381995

posted @ 2022-10-25 21:21  海乐学习  阅读(1231)  评论(0编辑  收藏  举报