Unicode编码

package com.abc.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by xxx.
 */
public class YxUnicodeUtil {
    private static YxUnicodeUtil instance = null;

    public YxUnicodeUtil() {}

    public static YxUnicodeUtil getInstance() {
        if (instance == null) {
            instance = new YxUnicodeUtil();
        }

        return instance;
    }

    /**
     * @Title: unicodeEncode
     * @Description: unicode编码
     * @param str
     * @return
     */
    public String unicodeEncode(String str) {
        char[] utfBytes = str.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    /**
     * @Title: unicodeDecode
     * @Description: unicode解码
     * @param str
     * @return
     */
    public String unicodeDecode(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;
    }
}

 

posted @ 2020-11-17 11:22  都是城市惹的祸  阅读(67)  评论(0)    收藏  举报