博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java检测文本(字节流)的编码方式
阅读量:4112 次
发布时间:2019-05-25

本文共 1940 字,大约阅读时间需要 6 分钟。

需求:

某文件或者某字节流要检测他的编码格式。

实现:

基于jchardet

net.sourceforge.jchardet
jchardet
1.0

 

代码如下:

public class DetectorUtils {	private DetectorUtils() {	}	static class ChineseCharsetDetectionObserver implements			nsICharsetDetectionObserver {		private boolean found = false;		private String result;		public void Notify(String charset) {			found = true;			result = charset;		}		public ChineseCharsetDetectionObserver(boolean found, String result) {			super();			this.found = found;			this.result = result;		}		public boolean isFound() {			return found;		}		public String getResult() {			return result;		}	}	public static String[] detectChineseCharset(InputStream in)			throws Exception {		String[] prob=null;		BufferedInputStream imp = null;		try {			boolean found = false;			String result = Charsets.UTF_8.toString();			int lang = nsPSMDetector.CHINESE;			nsDetector det = new nsDetector(lang);			ChineseCharsetDetectionObserver detectionObserver = new ChineseCharsetDetectionObserver(					found, result);			det.Init(detectionObserver);			imp = new BufferedInputStream(in);			byte[] buf = new byte[1024];			int len;			boolean isAscii = true;			while ((len = imp.read(buf, 0, buf.length)) != -1) {				if (isAscii)					isAscii = det.isAscii(buf, len);				if (!isAscii) {					if (det.DoIt(buf, len, false))						break;				}			}			det.DataEnd();			boolean isFound = detectionObserver.isFound();			if (isAscii) {				isFound = true;				prob = new String[] { "ASCII" };			} else if (isFound) {				prob = new String[] { detectionObserver.getResult() };			} else {				prob = det.getProbableCharsets();			}			return prob;		} finally {			IOUtils.closeQuietly(imp);			IOUtils.closeQuietly(in);		}	}}

测试:

String file = "C:/3737001.xml";		String[] probableSet = DetectorUtils.detectChineseCharset(new FileInputStream(file));		for (String charset : probableSet) {			System.out.println(charset);		}

 依赖的jar参见附件

转载地址:http://wlqsi.baihongyu.com/

你可能感兴趣的文章
在JS中 onclick="save();return false;"return false是
查看>>
idea 有时提示找不到类或者符号
查看>>
matplotlib.pyplot.plot()参数详解
查看>>
MFC矩阵运算
查看>>
ubuntu 安装mysql
查看>>
c# 计算器
查看>>
C# 简单的矩阵运算
查看>>
gcc 常用选项详解
查看>>
c++输出文件流ofstream用法详解
查看>>
firewalld的基本使用
查看>>
Linux下SVN客户端使用教程
查看>>
Linux分区方案
查看>>
nc 命令详解
查看>>
如何使用 systemd 中的定时器
查看>>
git命令速查表
查看>>
linux进程监控和自动重启的简单实现
查看>>
OpenFeign学习(三):OpenFeign配置生成代理对象
查看>>
OpenFeign学习(四):OpenFeign的方法同步请求执行
查看>>
OpenFeign学习(五):OpenFeign请求结果处理及重试控制
查看>>
OpenFeign学习(六):OpenFign进行表单提交参数或传输文件
查看>>