导入pom.xml依赖 <dependency> <groupId>com.ibm.icu</groupId> <artifactId>icu4j</artifactId> <version>64.2</version> </dependency>
public class TestIcu { /** * 获取编码 * @throws IOException * @throws Exception */ public static String getEncode(byte[] data){ CharsetDetector detector = new CharsetDetector(); detector.setText(data); CharsetMatch match = detector.detect(); String encoding = match.getName(); //System.out.println("The Content in " + match.getName()); CharsetMatch[] matches = detector.detectAll(); //System.out.println("All possibilities"); for (CharsetMatch m : matches) { //System.out.println("CharsetName:" + m.getName() + " Confidence:" + m.getConfidence()); } return encoding; } public static String getEncode(InputStream data) throws IOException { CharsetDetector detector = new CharsetDetector(); detector.setText(data); CharsetMatch match = detector.detect(); String encoding = match.getName(); System.out.println("The Content in " + match.getName()); CharsetMatch[] matches = detector.detectAll(); System.out.println("All possibilities"); for (CharsetMatch m : matches) { System.out.println("CharsetName:" + m.getName() + " Confidence:" + m.getConfidence()); } return encoding; } public static void main(String[] args) { System.out.println(TestIcu.getEncode("111asdfasdfad fqwef asdfw".getBytes())); } }