如何判斷java.io.File所讀取的文件編碼

如何判斷java.io.File所讀取的文件編碼

###問題 java中涉及到文件讀取,就常常要考慮文件編碼問題。雖然程序中通常都指定UTF-8編碼,可是用戶總可能提交各類編碼的文件(特別是windows下用戶),若是對這些文件不作判斷就直接按照UTF-8的方式讀取的話,是確定會亂碼的。java

###解決方案 java原生並不支持文件編碼的判斷,通常都是read文件的前幾個字節來判斷,須要本身編寫工具類,判斷的編碼類型也比較少。最近找到了個開源的項目juniversalchardet,能比較優雅的完成這個任務。 使用方法也很簡單,下載它的jar包,按照官網的例子操做便可,固然這段代碼本身封裝成工具類最好了:git

import org.mozilla.universalchardet.UniversalDetector;
 
public class TestDetector {
  public static void main(String[] args) throws java.io.IOException {
    byte[] buf = new byte[4096];
    String fileName = args[0];
    java.io.FileInputStream fis = new java.io.FileInputStream(fileName);
 
    // (1)
    UniversalDetector detector = new UniversalDetector(null);
 
    // (2)
    int nread;
    while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
      detector.handleData(buf, 0, nread);
    }
    // (3)
    detector.dataEnd();
 
    // (4)
    String encoding = detector.getDetectedCharset();
    if (encoding != null) {
      System.out.println("Detected encoding = " + encoding);
    } else {
      System.out.println("No encoding detected.");
    }
 
    // (5)
    detector.reset();
  }
}

我本身寫成工具類測試的時候,發現有些文件仍是不能判斷出來(好比excel保存過的gbk編碼的.csv文件),因此使用它判斷文件編碼的時候,最好處理下得不到編碼的狀況,好比給個默認編碼啥的。github

###juniversalchardet的項目地址windows

  1. googlecode
  2. github
相關文章
相關標籤/搜索