在记录用户从app传过来的信息时可能会带有emoji表情符,但是MySql存储不了,保存时会报异常,想让MySql存储emoji表情可以将数据库的字符集调整为utf8mb4格式,但是只有5.5.3以上的版本才会有这样的编码,但是总不能为了这么个表情升级服务器的数据库,可以使用工具类进行转换,存储的时候转换一次,取出来以后再转换回来即可解决这个问题
public class EmojiUtil {
/**
* 将str中的emoji表情转为byte数组
*
* @param str
* @return
*/
public static String resolveToByteFromEmoji(String str) {
Pattern pattern = Pattern
.compile("[^(\u2E80-\u9FFF\\w\\s`~!@#\\$%\\^&\\*\\(\\)_+-?()——=\\[\\]{}\\|;。,、《》”:;“!……’:'\"\\.?/\\\\*)]");
Matcher matcher = pattern.matcher(str);
StringBuffer sb2 = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb2, resolveToByte(matcher.group(0)));
}
matcher.appendTail(sb2);
return sb2.toString();
}
/**
* 将str中的byte数组类型的emoji表情转为正常显示的emoji表情
*
* @param str
* @return
*/
public static String resolveToEmojiFromByte(String str) {
Pattern pattern2 = Pattern.compile("<:>");
Matcher matcher2 = pattern2.matcher(str);
StringBuffer sb3 = new StringBuffer();
while (matcher2.find()) {
matcher2.appendReplacement(sb3, resolveToEmoji(matcher2.group(0)));
}
matcher2.appendTail(sb3);
return sb3.toString();
}
private static String resolveToByte(String str) {
byte[] b = str.getBytes();
StringBuffer sb = new StringBuffer();
sb.append("<:>
for (int i = 0; i
if (i
sb.append(Byte.valueOf(b[i]).toString() + ",");
} else {
sb.append(Byte.valueOf(b[i]).toString());
}
}
sb.append(":>");
return sb.toString();
}
private static String resolveToEmoji(String str) {
str = str.replaceAll("<:>", "");
String[] s = str.split(",");
byte[] b = new byte[s.length];
for (int i = 0; i
b[i] = Byte.valueOf(s[i]);
}
return new String(b);
}
/**
* 将byte数组类型的emoji表情替换为指定的字符串
*
* @param str
* @param replace
* @return
*/
public static String replaceEmojiFromByte(String str, String replace) {
return str.replaceAll("<:>", replace);
}
}