当文本包含Emoji字符的时候,存储到数据库或读取的时候需要进行编码和解码(如UTF_8),否则MySQL的存储可能有异常。
当有的文本不允许输入Emoji字符,或者显示时需要将Emoji替换为指定字符的时候可以用下面的几个工具方法。
/** * 将字符串中的Emoji表情替换为* * @param source * @return */ public static String replaceEmojiToStar(String source){ String res = ""; if (Tools.isStrEmpty(source)) { return res; } if(!containsEmoji(source)){ return source; }else{ int len = source.length(); char[] dest = new char[len]; for (int i = 0; i < len; i++) { char codePoint = source.charAt(i); if (isNotEmojiCharacter(codePoint)) { dest[i] = codePoint; }else{ dest[i] = '*'; } } res = String.valueOf(dest); } return res; } /** * 检测是否有emoji字符 * * @param source * @return 一旦含有就抛出 */ public static boolean containsEmoji(String source) { if (Tools.isStrEmpty(source)) { return false; } int len = source.length(); for (int i = 0; i < len; i++) { char codePoint = source.charAt(i); if (!isNotEmojiCharacter(codePoint)) { return true; } } return false; } /** * 判断是否是非Emoji字符之外的正常字符,正常字符返回true * @param codePoint * @return */ private static boolean isNotEmojiCharacter(char codePoint) { return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)); }