---
title: "String编码(五) 文件编码检测"
author: "orange5458"
date: "2013-03-26T11:13:09Z"
tags: []
categories: ["编程语言"]
slug: "string"
draft: false
lastmod: "2013-03-26T11:14:57Z"
id: 1836294
url: "https://orange5458.iteye.com/blog/1836294"
---

1.简介

为了防止读取编码不确定的文本文件时出现乱码现象，我们需要通过一种方法来自动检测文件内容的编码。

2.方法

1）通过BOM(Byte Order Mark)来检测

BOM是一组出险在字节流头位置的字节，用于标识字节的编码格式。例如：

UTF-8开头的EF BB BF

UTF-16开头的FF FE

UTF-16BE开头的FE FF

但是并不是所有的编码都有BOM，并且有些文件会省略BOM。

1.1）实现

```
package com.siyuan.jdk.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileTypeTest {
	
	public static final byte[] FILE_ENCODING_PREFIX_UTF8 = new byte[]{(byte)0xef, (byte)0xbb, (byte)0xBF};
	
	public static final byte[] FILE_ENCODING_PREFIX_UNICODE = new byte[]{(byte)0xff, (byte)0xfe};
	
	public static final byte[] FILE_ENCODING_PREFIX_UNICODEBE = new byte[]{(byte)0xfe, (byte)0xff};
	
	private static boolean isUTF8(File file) throws IOException {
		return isFileEncodingMatch(file, FILE_ENCODING_PREFIX_UTF8);
	}
	
	private static boolean isUnicode(File file) throws IOException {
		return isFileEncodingMatch(file, FILE_ENCODING_PREFIX_UNICODE);
	}
	
	private static boolean isUnicodeBE(File file) throws IOException {
		return isFileEncodingMatch(file, FILE_ENCODING_PREFIX_UNICODEBE);
	}
	
	private static boolean isFileEncodingMatch(File file, byte[] encodingPrefix) throws IOException {
		boolean matched = true;
		InputStream input = null;
		try {
			input = new FileInputStream(file);
			byte[] filePrefix = new byte[encodingPrefix.length];
			input.read(filePrefix);
			for (int i = 0; i < encodingPrefix.length; i ++) {
				if (encodingPrefix[i] != filePrefix[i]) {
					matched = false;
					break;
				}
			}
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
				}
			}
		}
		return matched;
	}
	
	public static String getFileEncoding(File file) throws IOException {
		if (!file.isFile() || !file.exists())
			throw new IllegalArgumentException("File whose encoding type need to be detected is not existed.");
		if (isUTF8(file)) 
			return "UTF-8";
		if (isUnicode(file)) 
			return "Unicode";
		if (isUnicodeBE(file)) 
			return "Unicode big endian";
		return null;
	}
	
	public static void main(String[] args) throws IOException {
		File file = new File("D:/FileReaderTest");
		if (file.isDirectory()) {
			for (File tmp : file.listFiles()) {
				System.out.println("Encoding type of file " + tmp.getAbsolutePath() + " is " + getFileEncoding(tmp));
			}
		} else {
			System.out.println("Encoding type of file " + file.getAbsolutePath() + " is " + getFileEncoding(file));
		}
	}

}
```

1.2）测试

在D:/FileReaderTest中创建文件

fileReaderTest-GBK.txt

fileReaderTest-Unicode.txt

fileReaderTest-UnicodeBE.txt

fileReaderTest-UTF8.txt

GBK.txt

Unicode.txt

UTF8.txt

文件编码格式如文明名所示，fileReaderTest\*.txt由windows创建，其余三个由eclipse创建。

程序运行结果

```
Encoding type of file D:\FileReaderTest\fileReaderTest-GBK.txt is null
Encoding type of file D:\FileReaderTest\fileReaderTest-Unicode.txt is Unicode
Encoding type of file D:\FileReaderTest\fileReaderTest-UnicodeBE.txt is Unicode big endian
Encoding type of file D:\FileReaderTest\fileReaderTest-UTF8.txt is UTF-8
Encoding type of file D:\FileReaderTest\GBK.txt is null
Encoding type of file D:\FileReaderTest\Unicode.txt is Unicode big endian
Encoding type of file D:\FileReaderTest\UTF8.txt is null
```

1.3）结论

通过简单的BOM并不能有效地判断出文件的编码方式，可靠性太低，不具有实用性。

2）通过第三方库检测

1.1）关于cpdetector

一个用于自动检测文件的第三方开源库。

核心接口

ICodepageDetector

|-open(URL url) : Reader

检测url对应的资源的charset，并返回对应的Reader对象

|-detectCodepage(InputStream in, int length) : Charset

检测字节流in的charset

|-detectCodepage(URL url) : Charset

检测url对应资源的charset

实现类

1.1.1）ASCIIDetector

用于检测资源是否为ASCII编码，每个字节都在0X00~0X7F之间，必须放在最后，因为某些编码的字节也处于那个区间。

1.1.2）ByteOrderMarkDetector

通过BOM来检测资源编码，支持的编码有：

00 00 FE FF UCS-4, big-endian machine (1234 order) FF FE 00 00 UCS-4,little-endian machine (4321 order) 00 00 FF FE UCS-4, unusual octet order (2143) FE FF 00 00 UCS-4, unusual octet order (3412) FE FF ## ## UTF-16, big-endian FF FE ## ## UTF-16, little-endian EF BB BF UTF-8

 

1.1.3）CodepageDetectorProxy

代理类，内部维护一个Set&lt;ICodepageDetector&gt;，迭代集合元素检测资源编码，返回第一个成功结果。

1.1.4）HTMLCodepageDetector

过期，已被ParsingDetector替换。

1.1.5）JChardetFacade

适配类，底层使用jchardet，

它是"A composite approach to language/encoding detection"的JAVA实现，具体逻辑如下

[http://www-archive.mozilla.org/projects/intl/UniversalCharsetDetection.html](http://www-archive.mozilla.org/projects/intl/UniversalCharsetDetection.html)

综合三种方法来检测资源编码，简述如下

(1)Coding Scheme Method

通过编码的字节规则特殊性来判断

(2)Character Distribution Method

通过字符的分布规则来判断

(3)Two-Char Sequence Distribution Method

通过两个字符的分布规则来判断

1.1.6）ParsingDetector

适配类，底层使用ANLTR，通过HTML和XML中charset的元素来获取charset。

1.1.7）UnicodeDetector

和ByteOrderMarkDetector一致。

1.2）使用

FileEncodingDetector.java

```
package com.siyuan.cpdetectortest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.ByteOrderMarkDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;

public class FileEncodingDetector {

	private CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
	
	public FileEncodingDetector() {
		detector.add(new ByteOrderMarkDetector()); 
		detector.add(new ParsingDetector(false));
		detector.add(JChardetFacade.getInstance());
		detector.add(ASCIIDetector.getInstance());
	}
	
	public String detect(File file) throws MalformedURLException, IOException {
		if (!file.isFile() || !file.exists())
			throw new IllegalArgumentException("File whose encoding type is to be detected must exist.");
		return detector.detectCodepage(new BufferedInputStream(new FileInputStream(file)), 1024).name();
	}
	
}
```

FileEncodingDetectorTest.java

```
package com.siyuan.cpdetectortest.test;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import com.siyuan.cpdetectortest.FileEncodingDetector;

public class FileEncodingDetectorTest {

	public static void main(String[] args) throws MalformedURLException, IOException {
		FileEncodingDetector fcDetector = new FileEncodingDetector();
		File dir = new File("D:/FileReaderTest");
		for (File file : dir.listFiles()) 
			System.out.println("Encoding type of " + file.getName() + " is " + fcDetector.detect(file));
	}

}
```

 1.3）测试

运行FileEncodingDetectorTest.java，结果如下

```
Encoding type of fileReaderTest-GBK.txt is GB2312
Encoding type of fileReaderTest-Unicode.txt is UTF-16LE
Encoding type of fileReaderTest-UnicodeBE.txt is UTF-16BE
Encoding type of fileReaderTest-UTF8.txt is UTF-8
Encoding type of GBK.txt is GB2312
Encoding type of Unicode.txt is UTF-16BE
Encoding type of UTF8.txt is UTF-8
```

 1.4）参考资料

[http://cpdetector.sourceforge.net/](http://cpdetector.sourceforge.net/)