ToolUtils.java 1.1 KB

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