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