可以使用Hutool中的CharsetType类和UnicodeUtil类,代码如下:

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.UnicodeUtil;

public class Test {
    public static void main(String[] args) {
        String str = '测试字符串abc';
        String charset = CharsetUtil.GBK;
        boolean hasNonGBK = StrUtil.containsIgnoreCase(str, charset);

        if (hasNonGBK) {
            str = UnicodeUtil.toUnicode(str);
        }

        System.out.println(str);
    }
}

首先使用StrUtil.containsIgnoreCase()方法判断字符串中是否包含GBK编码中不存在的字符,如果存在则将整个字符串转换为unicode编码。

Java Hutool 判断字符串非GBK编码并转Unicode

原文地址: https://www.cveoy.top/t/topic/ofHt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录