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