一个byte数组,byte[] buf,是由一个字符串转换来的,如何判断字符串使用的是什么编码?
Mozilla的一个组件提供了相应功能:
组件叫,juniversalchardet,下载地址:https://juniversalchardet.googlecode.com/files/juniversalchardet-1.0.3.jar
也可以到组件官网下载最新版本:https://code.google.com/p/juniversalchardet/
public static String guessEncoding(byte[] bytes) {
String DEFAULT_ENCODING = "UTF-8";
org.mozilla.universalchardet.UniversalDetector detector =
new org.mozilla.universalchardet.UniversalDetector(null);
detector.handleData(bytes, 0, bytes.length);
detector.dataEnd();
String encoding = detector.getDetectedCharset();
detector.reset();
if (encoding == null) {
encoding = DEFAULT_ENCODING;
}
return encoding;
}
本文介绍了一个名为juniversalchardet的组件,该组件可以用于猜测字节数组对应的字符编码方式。通过提供的静态方法guessEncoding,可以方便地检测出字符串使用的编码格式,默认采用UTF-8作为备选编码。
850

被折叠的 条评论
为什么被折叠?



