檢測檔案編碼類別型

來源:互聯網
上載者:User

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 包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.