编码

java 寻梦 5年前 (2019-12-31) 524次浏览 0个评论 扫描二维码

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;
}

喜欢 (0)
[支付宝扫码,感谢支持]
分享 (0)
关于作者:

您必须 登录 才能发表评论!