emoji表情符在平時用的時候特別的爽,但是有時候在開發的時候就比較的難受,微信開發暱稱往往都有表情符導致無法入庫。嘗試了往上很多的方法都沒有得以解決,甚至我改了數據庫配置後發現庫不能啓動了(哎喲我靠,感謝那些博主的建議)。所以今天給大家個工具類,用着是挺舒服的。
public class EmojiUtil {
/**
* @Description emoji表情轉換入庫
* @param str 待轉換字符串
* @return 轉換後字符串
* @throws UnsupportedEncodingException
*/
public static String emojiToUtf(String str)
throws UnsupportedEncodingException {
String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);
StringBuffer con = new StringBuffer();
while (matcher.find()) {
try {
matcher.appendReplacement(con,"[[" + URLEncoder.encode(matcher.group(1),"UTF-8") + "]]");
} catch (UnsupportedEncodingException e) {
throw e;
}
}
matcher.appendTail(con);
return con.toString();
}
/**
* @Description 還原emoji表情的字符串
* @param str 轉換後的字符串
* @return 轉換前的字符串
* @throws UnsupportedEncodingException
*/
public static String utfToEmoji(String str)
throws UnsupportedEncodingException {
String patternString = "\\[\\[(.*?)\\]\\]";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);
StringBuffer con = new StringBuffer();
while (matcher.find()) {
try {
matcher.appendReplacement(con,
URLDecoder.decode(matcher.group(1), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw e;
}
}
matcher.appendTail(con);
return con.toString();
}
第一個方法是將字段中的emoji表情轉換入庫。
String content=“”;
try {
content = EmojiUtil.emojiToUtf(content);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
轉換後入庫。
第二個方法是講 轉化後的字符還原爲 emoji表情:
String content = comm.getStr("content");
if (StringUtils.isNotBlank(content)) {
try {
content = EmojiUtil.utfToEmoji(content);
comm.set("content", content);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
嗯,大概就是這個樣子。
給大家推薦一個公衆號裏面有很多的學習資料、視頻挺不錯的。