EncodingUtils { public static String detectEncoding(byte[] data, String defaultEncoding) throws IOException { CharsetDetector detector = new CharsetDetector(); detector.setText(data); CharsetMatch cm = detector.detect(); String estimatedEncoding = cm.getName(); boolean isReliable = Charset.isSupported(estimatedEncoding) && cm.getConfidence() >= MINIMAL_CONFIDENCE_LEVEL; return isReliable ? estimatedEncoding : defaultEncoding; }  static String getAutoDecodedString(byte[] data, String defaultEncoding); static String detectEncoding(byte[] data, String defaultEncoding); static String encodePathWithUTF8(String path); static String decodePathWithUTF8(String path);  }
@Test public void testGetAutoDecodedStringChinese() throws IOException { String testStr = "12345678ikbsdfghjklsd你好lzxcvbnm,.:LGF)(&^%^RYVG"; String rtnEncode = EncodingUtils.detectEncoding(testStr.getBytes("EUC-KR"), "EUC-KR"); assertThat(rtnEncode, is("EUC-KR")); }
@Test public void testDetectEncoding() throws IOException { String testStr = "12345678ikbsdfghjklsd你好lzxcvbnm,.:LGF)(&^%^RYVG"; String rtnStr = EncodingUtils.getAutoDecodedString(testStr.getBytes("UTF-8"), "UTF-8"); assertThat(rtnStr, is(testStr)); }