遇到这个问题是在测试时发现用的是mysql,字符集为utf8,查到各路大神的办法,需要修改表的字符集为utf8mb4,但是试了很多次,无果~
于是尝试用java来实现,其实主要就是入库时用正则将表情转为字符,然后从库中取出时为string:
1 /** 2 * 将str中的emoji表情转为byte数组 3 * 4 * @param str 5 * @return 6 */ 7 public static String resolveToByteFromEmoji(String str) { 8 Pattern pattern = Pattern 9 .compile("[^(\u2E80-\u9FFF\\w\\s`~!@#\\$%\\^&\\*\\(\\)_+-?()——=\\[\\]{}\\|;。,、《》”:;“!……’:'\"<,>\\.?/\\\\*)]"); 10 Matcher matcher = pattern.matcher(str); 11 StringBuffer sb2 = new StringBuffer(); 12 while (matcher.find()) { 13 matcher.appendReplacement(sb2, resolveToByte(matcher.group(0))); 14 } 15 matcher.appendTail(sb2); 16 return sb2.toString(); 17 } 18 19 /** 20 * 将str中的byte数组类型的emoji表情转为正常显示的emoji表情 21 * 22 * @param str 23 * @return 24 */ 25 public static String resolveToEmojiFromByte(String str) { 26 Pattern pattern2 = Pattern.compile("<:([[-]\\d*[,]]+):>"); 27 Matcher matcher2 = pattern2.matcher(str); 28 StringBuffer sb3 = new StringBuffer(); 29 while (matcher2.find()) { 30 matcher2.appendReplacement(sb3, resolveToEmoji(matcher2.group(0))); 31 } 32 matcher2.appendTail(sb3); 33 return sb3.toString(); 34 } 35 36 private static String resolveToByte(String str) { 37 byte[] b = str.getBytes(); 38 StringBuffer sb = new StringBuffer(); 39 sb.append("<:"); 40 for (int i = 0; i < b.length; i++) { 41 if (i < b.length - 1) { 42 sb.append(Byte.valueOf(b[i]).toString() + ","); 43 } else { 44 sb.append(Byte.valueOf(b[i]).toString()); 45 } 46 } 47 sb.append(":>"); 48 return sb.toString(); 49 } 50 51 private static String resolveToEmoji(String str) { 52 str = str.replaceAll("<:", "").replaceAll(":>", ""); 53 String[] s = str.split(","); 54 byte[] b = new byte[s.length]; 55 for (int i = 0; i < s.length; i++) { 56 b[i] = Byte.valueOf(s[i]); 57 } 58 return new String(b); 59 }
因为表情都是有规律的,都是以<:开始:>结束~所以自然就有办法解决啦~~
————————————————
版权声明:本文为CSDN博主「wangdan199112」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wangdan199112/java/article/details/53290154