zl程序教程

您现在的位置是:首页 >  其他

当前栏目

编码

2023-06-13 09:15:25 时间

1 GB18030字节数组转UTF-8字符串

public static String gB18030ByteArrayToUtf8String(byte[] bytes) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        CharBuffer gb18030 = Charset.forName("GB18030").decode(byteBuffer);
        ByteBuffer utf8 = Charset.forName("UTF8").encode(gb18030);
        return new String(utf8.array());
    }

2 字符串转GB18030字节数组

   public static byte[] utf8ToGb18030ByteArray(String str) {
        ByteBuffer gb18030 = Charset.forName("GB18030").encode(str);
        return gb18030.array();
    }

3 获取字节数组编码格式

#--导入 
#compile group: 'com.googlecode.juniversalchardet', name: 'juniversalchardet', version: '1.0.3'

public static String getEncoding(byte[] bytes) {
    String DEFAULT_ENCODING = "UTF-8";
    UniversalDetector detector =new UniversalDetector(null);
    detector.handleData(bytes, 0, bytes.length);
    detector.dataEnd();
    String encoding = detector.getDetectedCharset();
    detector.reset();
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }
    return encoding;
}