处理mysql utf-8 无法保存emoji表情的问题(不改数据库配置)

对mysql中无法保存的emoji表情进行部分编码

package com.centaline.answer.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 处理mysql utf-8的问题
public class EmojiUtil {
    public static String encode(String reviewerName) throws UnsupportedEncodingException {
        Pattern pattern = Pattern.compile("[^\\u0000-\\uFFFF]");
        Matcher matcher = pattern.matcher(reviewerName);
        List list = new ArrayList<>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        for (String string : list) {
            reviewerName = reviewerName.replaceAll(string, "[[Emoji[" + URLEncoder.encode(string, "utf-8") + "]]]");
        }
        return reviewerName;
    }

    public static String decode(String reviewerName) throws UnsupportedEncodingException {

        Pattern pattern = Pattern.compile("\\[\\[Emoji\\[.*?\\]\\]\\]");
        Matcher matcher = pattern.matcher(reviewerName);
        List list = new ArrayList<>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        for (String string : list) {
            String tmp = string.replace("[[Emoji[", "").replaceAll("]]]", "");
            reviewerName = reviewerName.replace(string, URLDecoder.decode(tmp, "utf-8"));
        }
        return reviewerName;

    }

}

你可能感兴趣的:(处理mysql utf-8 无法保存emoji表情的问题(不改数据库配置))