[Java] utf-8异常编码过滤 →→→→→进入此内容的聊天室

来自 , 2021-05-02, 写在 Java, 查看 127 次.
URL http://www.code666.cn/view/1e056d2b
  1. public static String filterOffUtf8Mb4(String text)throws UnsupportedEncodingException {
  2.         byte[] bytes = text.getBytes("utf-8");
  3.         ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
  4.         int i = 0;
  5.         while (i < bytes.length) {
  6.                 short b = bytes[i];
  7.                         if (b > 0) {
  8.                                 buffer.put(bytes[i++]);
  9.                                 continue;
  10.                         }
  11.                         b += 256;
  12.                         if ((b ^ 0xC0) >> 4 == 0) {
  13.                                 buffer.put(bytes, i, 2);
  14.                                 i += 2;
  15.                         }
  16.                         else if ((b ^ 0xE0) >> 4 == 0) {
  17.                                 buffer.put(bytes, i, 3);
  18.                                 i += 3;
  19.                         }
  20.                         else if ((b ^ 0xF0) >> 4 == 0) {
  21.                                 i += 4;
  22.                         }
  23.                         // 添加处理如b的指为-48等情况出现的死循环
  24.                         else {
  25.                                 buffer.put(bytes[i++]);
  26.                                 continue;
  27.                         }
  28.  
  29.                 }
  30.  
  31.                 buffer.flip();
  32.  
  33.                 return new String(buffer.array(), "utf-8");
  34.         }

回复 "utf-8异常编码过滤"

这儿你可以回复上面这条便签

captcha