java-將評論內容過濾特殊表情emoj符號,保存到mysql中


正常操作評論,保存時,若評論內容含有特殊表情符號,后台將報錯如下:

Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '='; nested exception is java.sql.SQLException: Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '='

后來查閱資料,找到方法將其評論內容中特殊符號過濾掉,然后保存。廢話不多說,直接上代碼:

 1 /**
 2      * 檢測是否有emoji字符
 3      * @param source
 4      * @return 一旦含有就拋出
 5      */
 6     public static boolean containsEmoji(String source) {
 7         if (StringUtils.isBlank(source)) {
 8             return false;
 9         }
10 
11         int len = source.length();
12 
13         for (int i = 0; i < len; i++) {
14             char codePoint = source.charAt(i);
15 
16             if (isEmojiCharacter(codePoint)) {
17                 //do nothing,判斷到了這里表明,確認有表情字符
18                 return true;
19             }
20         }
21 
22         return false;
23     }
24 
25     private static boolean isEmojiCharacter(char codePoint) {
26         return (codePoint == 0x0) ||
27                 (codePoint == 0x9) ||
28                 (codePoint == 0xA) ||
29                 (codePoint == 0xD) ||
30                 ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
31                 ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
32                 ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
33     }
34 
35     /**
36      * 過濾emoji 或者 其他非文字類型的字符
37      * @param source
38      * @return
39      */
40     public static String filterEmoji(String source) {
41 
42         if (!containsEmoji(source)) {
43             return source;//如果不包含,直接返回
44         }
45         //到這里鐵定包含
46         StringBuilder buf = null;
47 
48         int len = source.length();
49 
50         for (int i = 0; i < len; i++) {
51             char codePoint = source.charAt(i);
52 
53             if (isEmojiCharacter(codePoint)) {
54                 if (buf == null) {
55                     buf = new StringBuilder(source.length());
56                 }
57 
58                 buf.append(codePoint);
59             } else {
60             }
61         }
62 
63         if (buf == null) {
64             return source;//如果沒有找到 emoji表情,則返回源字符串
65         } else {
66             if (buf.length() == len) {//這里的意義在於盡可能少的toString,因為會重新生成字符串
67                 buf = null;
68                 return source;
69             } else {
70                 return buf.toString();
71             }
72         }
73 
74     }
Java Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM