package com.tzld.piaoquan.wecom.utils; import java.nio.charset.StandardCharsets; public class ToolUtils { public static String truncateString(String input, int maxBytes) { if (input == null || maxBytes <= 0) { return ""; } byte[] bytes = input.getBytes(StandardCharsets.UTF_8); if (bytes.length <= maxBytes) { return input; // 如果字节数已经在限制内,直接返回原字符串 } // 截取字节数组 byte[] truncatedBytes = new byte[maxBytes]; System.arraycopy(bytes, 0, truncatedBytes, 0, maxBytes); // 将截取的字节数组转换回字符串 String truncatedString = new String(truncatedBytes, StandardCharsets.UTF_8); // 处理可能的字符截断问题 // 如果截取后字符串的字节数仍然大于 maxBytes,向前查找直到找到有效字符 while (truncatedString.getBytes(StandardCharsets.UTF_8).length > maxBytes) { truncatedString = truncatedString.substring(0, truncatedString.length() - 1); } return truncatedString; } }