java去除非utf8编码,并将乱码用“?“替换

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
@Slf4j
public class CodeUtil {
    public static String filterOffUtf8Mb4(String text) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(text)) {
            return text;
        }
        byte[] bytes = text.getBytes("UTF-8");
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        int i = 0;
        while (i < bytes.length) {
            short b = bytes[i];
            if (b > 0) {
                buffer.put(bytes[i++]);
                continue;
            }
            b += 256;
            if ((b ^ 0xC0) >> 4 == 0) {
                buffer.put(bytes, i, 2);
                i += 2;
            } else if ((b ^ 0xE0) >> 4 == 0) {
                buffer.put(bytes, i, 3);
                i += 3;
            } else if ((b ^ 0xF0) >> 4 == 0) {
                i += 4;
            }else{
                i+=1;
            }
        }
        buffer.flip();
        String delStr = new String(buffer.array(), "utf-8");
        if (text.equals(delStr)) {
            return text;
        }
//        非utf8编码字符替换为'?'
        byte[] delBytes = delStr.getBytes("UTF-8");
        int j = 0;
        int n = 0;
        ByteBuffer buffer2 = ByteBuffer.allocate(bytes.length);
        while (j < bytes.length) {
            if (bytes[j] != delBytes[j - n]) {
                bytes[j] = 63;
                n++;
            }
            buffer2.put(bytes[j++]);
        }

        buffer2.flip();
        String str = new String(buffer2.array(), "utf-8");
        return str;
    }

    public static String decode(String str) {

        byte[] bt = null;
        String decodeStr = null;
        try {
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            bt = decoder.decodeBuffer(str);
            decodeStr = new String(new String(bt, "GBK").getBytes(), "utf-8");
        } catch (IOException e) {
            log.error("解码失败");
            e.printStackTrace();
            return "解码失败";
        }
        return decodeStr;
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值