校验字符串编码工具类

校验字符串编码工具类

//知识点
//str.equals(new String(str.getBytes(), encode)):校验编码
//系统默认编码:System.getProperty("file.encoding")
//系统默认字符编码:Charset.defaultCharset()
//系统默认语言编码:System.getProperty("user.language")

package base.util;

import java.nio.charset.Charset;

/**
 * @author 马家立
 * @version 创建时间:2019年12月7日下午5:47:49
 * @Description:TODO 校验字符串编码工具类
 */

public class EncodingUtil {
    /**
     * @Title:getEncoding
     * @author:马家立
     * @date:2019年12月7日 下午6:02:27
     * @Description:TODO 校验字符串编码
     * @param str--待识别编码的字符串
     * @return String
     */
    public static String getEncoding(String str) {
        String encode = "未识别编码格式";
        try {
            encode = "UTF-16";
            if (str.equals(new String(str.getBytes(), encode))) {
                return encode;
            }
            encode = "UTF-8";
            if (str.equals(new String(str.getBytes(), encode))) {
                return encode;
            }
            encode = "ASCII";
            if (str.equals(new String(str.getBytes(), encode))) {
                return "字符串<< " + str + " >>中仅由数字和英文字母组成,无法识别其编码格式";
            }
            encode = "ISO-8859-1";
            if (str.equals(new String(str.getBytes(), encode))) {
                return encode;
            }
            encode = "GB2312";
            if (str.equals(new String(str.getBytes(), encode))) {
                return encode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encode;
    }

    /**
     * @Title:isEncoding
     * @author:马家立
     * @date:2019年12月7日 下午6:12:17
     * @Description:TODO 校验字符串是否是传入参数编码
     * @param str--待校验的字符串
     * @param encode--字符编码:UTF-16,UTF-8,ASCII,ISO-8859-1,GB2312等
     * @return boolean
     */
    public static boolean isEncoding(String str, String encode) {
        try {
            if (str.equals(new String(str.getBytes(), encode))) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        /**
         * --测试字符串编码
         */
        System.out.println("系统默认编码:" + System.getProperty("file.encoding"));
        System.out.println("系统默认字符编码:" + Charset.defaultCharset());
        System.out.println("系统默认语言编码:" + System.getProperty("user.language"));
        String hello = "hello, 我来了!";
        System.out.println("'hello, 我来了!'的编码是:" + getEncoding(hello));
        /**
         * --校验字符串编码
         */
        String str = "校验编码是否是UTF8";
        // 校验字符串是否是UTF-8
        boolean isUTF8 = isEncoding(str, "UTF-8");
        if (isUTF8) {
            System.out.println("该字符串是UTF-8");
        } else {
            System.out.println("该字符串不是UTF-8");
        }
    }
}

代码运行结果如下:

猜你喜欢

转载自www.cnblogs.com/mjtabu/p/12002861.html
今日推荐