Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何按字节大小截断包含表情符号的字符串_Java_Emoji - Fatal编程技术网

Java 如何按字节大小截断包含表情符号的字符串

Java 如何按字节大小截断包含表情符号的字符串,java,emoji,Java,Emoji,我想将UTF-8字符集大小的字符串限制为30字节,我找到了一个解决方案 因此,我在此基础上创建了一个方法 public static String truncateTextByByteLimit(String message, int byteLimit) { String result = ""; try { Charset utf8Charset = Charset.forName("UTF-8"); CharsetDecoder cd = u

我想将UTF-8字符集大小的字符串限制为30字节,我找到了一个解决方案

因此,我在此基础上创建了一个方法

public static String truncateTextByByteLimit(String message, int byteLimit) {
    String result = "";
    try {
        Charset utf8Charset = Charset.forName("UTF-8");
        CharsetDecoder cd = utf8Charset.newDecoder();
        byte[] utf8Bytes = message.getBytes(utf8Charset);
        System.out.println("check message: " + message + " /length: " +message.length()+ " //byte length: " + utf8Bytes.length + "/limit: " + byteLimit + " /codePoint: " +message.codePointCount(0, message.length()));
        ByteBuffer bb = ByteBuffer.wrap(utf8Bytes, 0, byteLimit);
        CharBuffer cb = CharBuffer.allocate(byteLimit);
        // Ignore an incomplete character
        cd.onMalformedInput(CodingErrorAction.IGNORE);
        cd.decode(bb, cb, true);
        cd.flush(cb);
        result = new String(cb.array(), 0, cb.position());
        if (result.length()<=0) {
            return truncateTextByByteLimit(message, (byteLimit+1));
        } else {
            return result;
        }
    } catch (Exception e) {
        e.printStackTrace();

        return message;
    }
}
我的调试消息显示
检查消息:让我们用
ByteBuffer#包装一下允许的长度

要使用的子阵列的长度;必须为非负且不大于
array.length-offset
。新缓冲区的限制将设置为
offset+length

为了解决这个问题,您需要取两个长度中的较小值——要么是绝对最大值
byteLimit
,要么是
utf8Bytes
数组的大小

ByteBuffer.wrap(utf8Bytes, 0, Math.min(utf8Bytes.length, byteLimit));
ByteBuffer.wrap(utf8Bytes, 0, Math.min(utf8Bytes.length, byteLimit));