Java 如何按字节大小截断包含表情符号的字符串
我想将UTF-8字符集大小的字符串限制为30字节,我找到了一个解决方案 因此,我在此基础上创建了一个方法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
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));