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

时间:2015-10-08 03:34:07

标签: java emoji

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

所以我在这个

上创建了一个方法
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;
    }
}

问题是我用以下表情符号测试String: System.out.println(truncateTextByByteLimit("let's \uD83D\uDE09", 30));

显示错误

java.lang.IndexOutOfBoundsException
at java.nio.ByteBuffer.wrap(ByteBuffer.java:371)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

我的调试信息显示 check message: let's /length: 8 //byte length: 10/limit: 30 /codePoint: 7

当我使用相同的消息和byteLimit测试小于或等于10时,它可以正常工作...

所以我不明白为什么它会显示java.lang.IndexOutOfBoundsException

1 个答案:

答案 0 :(得分:1)

ByteBuffer#wrap has a limitation关于允许的长度。

  

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

要解决这个问题,你需要取两个长度中较小的一个 - 要么它是你的绝对最大值byteLimit,要么它将是utf8Bytes数组的大小。

ByteBuffer.wrap(utf8Bytes, 0, Math.min(utf8Bytes.length, byteLimit));
相关问题