乐趣区

关于java:java-将表情转换成字符串存入数据库

/**
    * @Description 将字符串中的 emoji 表情转换成能够在 utf- 8 字符集数据库中保留的格局(表情占 4 个字节,须要 utf8mb4 字符集)* @param str
    * 待转换字符串
    * @return 转换后字符串
    * @throws UnsupportedEncodingException
    * exception
    */
    public static String emojiConvert1(String str)
    throws UnsupportedEncodingException {String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";
    
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            try {
                matcher.appendReplacement(
                sb,
                "[["
                + URLEncoder.encode(matcher.group(1),
                "UTF-8") + "]]");
            } catch(UnsupportedEncodingException e) {System.out.println(e);
                throw e;
            }
        }
        matcher.appendTail(sb);
        System.out.println("emojiConvert" + str + "to" + sb.toString()
        + ", len:" + sb.length());
        return sb.toString();}

    /**
    * @Description 还原 utf8 数据库中保留的含转换后 emoji 表情的字符串
    * @param str
    * 转换后的字符串
    * @return 转换前的字符串
    * @throws UnsupportedEncodingException
    * exception
    */
    public static String emojiRecovery2(String str)
        throws UnsupportedEncodingException {String patternString = "\\[\\[(.*?)\\]\\]";
    
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);
    
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            try {
                matcher.appendReplacement(sb,
                URLDecoder.decode(matcher.group(1), "UTF-8"));
            } catch(UnsupportedEncodingException e) {System.out.println(e);
                throw e;
            }
        }
        matcher.appendTail(sb);
        System.out.println("emojiRecovery" + str + "to" + sb.toString());
        return sb.toString();}
退出移动版