最近遇到外采产品中,编码不统一问题,故需要对编码进行转换并统一。
手工转换代价太大,这就需要能够通过编码的形式动态探测源文件的编码类型,而后在进行统一格式转换。
在转换过程中尝试通过编码直接去BOM来识别,但由于源文件编码类型很多,且很多不为常用和未知,转换工作很棘手。
在网络上找到一篇文章,发现Apache Tika能够很好的识别源文件的编码类型,这个工具解决了团队在转码过程中的大部分问题。
下面我们引用一下文章中的用例;
1、UniversalEncodingDetector类来识别文件编码:
public static void main(String[] args) throws IOException, TikaException {
// TODO Auto-generated method stub
File file=new File("[文件路径]");
InputStream stream=null;
try
{
stream=new FileInputStream(file);
EncodingDetector detector=new UniversalEncodingDetector();
Charset charset = detector.detect(new BufferedInputStream(stream), new Metadata());
System.out.println("编码:"+charset.name());
}
finally
{
if (stream != null) stream.close();
}
}
2、使用ICU4J包进行文档编码获取:
package com.huilan.dig.contoller;
import java.io.IOException;
import java.io.InputStream;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
/**
* 本类使用ICU4J包进行文档编码获取
*
*/
public class EncodeDetector {
/**
* 获取编码
* @throws IOException
* @throws Exception
*/
public static String getEncode(byte[] data,String url){
CharsetDetector detector = new CharsetDetector();
detector.setText(data);
CharsetMatch match = detector.detect();
String encoding = match.getName();
System.out.println("The Content in " + match.getName());
CharsetMatch[] matches = detector.detectAll();
System.out.println("All possibilities");
for (CharsetMatch m : matches) {
System.out.println("CharsetName:" + m.getName() + " Confidence:"
+ m.getConfidence());
}
return encoding;
}
public static String getEncode(InputStream data,String url) throws IOException{
CharsetDetector detector = new CharsetDetector();
detector.setText(data);
CharsetMatch match = detector.detect();
String encoding = match.getName();
System.out.println("The Content in " + match.getName());
CharsetMatch[] matches = detector.detectAll();
System.out.println("All possibilities");
for (CharsetMatch m : matches) {
System.out.println("CharsetName:" + m.getName() + " Confidence:"
+ m.getConfidence());
}
return encoding;
}
}
pom.xml:
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>1.7</version>
</dependency>
参考资料:
http://www.cnblogs.com/chenying99/archive/2013/03/07/2947296.html
http://blog.youkuaiyun.com/earbao/article/details/43150809