2011-11-25 31 views
0

可能重複:
How do I detect the encoding of some text?如何區分文本文件?

如何區分Unicode文本文件和其他文本文件?

我在做一個使用java的批量上傳文件。 首先我在excel文件中寫入輸入,然後保存爲Unicode文本(.txt)文件。 然後我會上傳Unicode文本文件,並從我的java類中讀取。

這裏我有一個問題。 我可以區分.txt文件和其他文本文件。但我怎麼能找到一個文件,無論是Unicode文本文件或其他文本文件。

回答

0

試試這個

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(); 
    } 
}