SpringBoot application.properties 添加中文值

SpringBoot application.properties 添加中文值

摘要

SpringBoot application.properties 添加中文值

application.properties中文乱码

application.properties中添加中文值的时候会有乱码
因为不能直接在application.properties中添加中文,需要先转换为unicode编码.

中文和unicode编码之间相互转换


public class test {

    public static void main(String[] args) {

        System.out.println(getUnicode("中文"));
        System.out.println(unicodeToString(getUnicode("中文")));

    }


    public static String getUnicode(String s) {
        try {
            StringBuffer out = new StringBuffer("");
            byte[] bytes = s.getBytes("unicode");
            for (int i = 0; i < bytes.length - 1; i += 2) {
                out.append("\\u");
                String str = Integer.toHexString(bytes[i + 1] & 0xff);
                for (int j = str.length(); j < 2; j++) {
                    out.append("0");
                }
                String str1 = Integer.toHexString(bytes[i] & 0xff);
                out.append(str1);
                out.append(str);

            }
            return out.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }


}