java对Emoji表情的忽略

最近做做移动端开发,用户输入Emoji表情时,
SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column 'review' at row 1

遵照以前的解决方案,把emoji表情的字符串过滤掉,然后存到数据库中;

根据字符编码来排除Emoji表情;
暂时不晓得js如何过滤掉Emoji表情,当然也是通过编码的方式吧!

写上java代码吧!!

package com.migoedu.mobile.common.Emoji;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by XXX on 2015/9/7.
 */
public class EmojiFilter {
    /**
     * 检测是否有emoji字符
     * @param source
     * @return 一旦含有就抛出
     */
    public static boolean containsWord(String source) {
        System.out.println(StringUtils.isBlank(source));
        if (StringUtils.isBlank(source)) {
            return false;
        }

        int len = source.length();
        System.out.println(len);
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isNotEmojiCharacter(codePoint)) {
                return true;
            }
        }

        return false;
    }


    private static boolean isNotEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {

        if (!containsWord(source)) {
            System.out.println("filterEmoji 不包含文字说明只有表情。");
            return "";//如果不包含,直接返回
        }
        //到这里铁定包含
        StringBuilder buf = null;

        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isNotEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }
                buf.append(codePoint);
            } else {
            }
        }

        if (buf == null) {
            return "";//如果没有可能到这步吧!
        } else {
            if (buf.length() == len) {//这里的意义在于尽可能少的toString,因为会重新生成字符串
                return source;
            } else {
                return buf.toString();
            }
        }

    }
}


你可能感兴趣的:(java对Emoji表情的忽略)