1 GB18030字节数组转UTF-8字符串
代码语言:javascript
复制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字节数组
代码语言:javascript
复制 public static byte[] utf8ToGb18030ByteArray(String str) {
ByteBuffer gb18030 = Charset.forName("GB18030").encode(str);
return gb18030.array();
}
3 获取字节数组编码格式
代码语言:javascript
复制#--导入
#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;
}