private static String geestFileEncoding(File file, nsDetector det) throws FileNotFoundException, IOException {<br />// Set an observer...<br />// The Notify() will be called when a matching charset is found. </p><p>final boolean[] found = new boolean[1];<br />final String[] encoding = new String[1];</p><p>det.Init(new nsICharsetDetectionObserver() {<br />public void Notify(String charset) {<br />found[0] = true;<br />encoding[0] = charset;<br />}<br />});<br />BufferedInputStream imp = new BufferedInputStream(new FileInputStream(file));<br />byte[] buf = new byte[1024];<br />int len;<br />boolean done = false;<br />boolean isAscii = true;<br />while ((len = imp.read(buf, 0, buf.length)) != -1) {<br />// Check if the stream is only ascii.<br />if (isAscii)<br />isAscii = det.isAscii(buf, len);<br />// DoIt if non-ascii and not done yet.<br />if (!isAscii && !done)<br />done = det.DoIt(buf, len, false);<br />}<br />det.DataEnd();<br />if (isAscii) {<br />encoding[0] = "ASCII";<br />found[0] = true;<br />}<br />if (!found[0]) {<br />String prob[] = det.getProbableCharsets();<br />if (prob.length > 0) {<br />// 在沒有發現情況下,則取第一個可能的編碼<br />encoding[0] = prob[0];<br />} else {<br />return null;<br />}<br />}<br />return encoding[0];<br />}
使用 jchardet開源項目中的chardet.jar 包