可能重复:
How do I detect the encoding of some text?
如何区分unicode文本文件和其他文本文件?
我正在使用java做一个批量上传文件。首先,我将输入写入excel文件,然后将其保存为Unicode文本(.txt)文件。然后,我将上传Unicode文本文件,并从我的java类中读取。
我有个问题。我可以区分.txt文件和文本文件以外的其他文件。但是,如何找到一个文件,无论是Unicode文本文件还是其他文本文件。
发布于 2011-11-25 07:59:55
尝尝这个
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();
}
}https://stackoverflow.com/questions/8265827
复制相似问题