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 @   海乐学习  阅读(1310)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示