首页>代码>java转换文本文件编码>/src/org/charsetconvert/CharsetDetector.java
package org.charsetconvert;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

public class CharsetDetector {

	private boolean found = false;
	private String result;
	private int lang;

	public String[] detectChineseCharset(InputStream in) throws IOException {
		lang = nsPSMDetector.CHINESE;
		String[] prob;
		// Initalize the nsDetector() ;
		nsDetector det = new nsDetector(lang);
		// Set an observer...
		// The Notify() will be called when a matching charset is found.

		det.Init(new nsICharsetDetectionObserver() {

			public void Notify(String charset) {
				found = true;
				result = charset;
			}
		});
		BufferedInputStream imp = new BufferedInputStream(in);
		byte[] buf = new byte[1024];
		int len;
		boolean isAscii = true;
		while ((len = imp.read(buf, 0, buf.length)) != -1) {
			// Check if the stream is only ascii.
			if (isAscii)
				isAscii = det.isAscii(buf, len);
			// DoIt if non-ascii and not done yet.
			if (!isAscii) {
				if (det.DoIt(buf, len, false))
					break;
			}
		}
		imp.close();
		in.close();
		det.DataEnd();
		if (isAscii) {
			found = true;
			prob = new String[] { "ASCII" };
		} else if (found) {
			prob = new String[] { result };
		} else {
			prob = det.getProbableCharsets();
		}
		return prob;
	}

	public String[] detectAllCharset(InputStream in) throws IOException {
		try {
			lang = nsPSMDetector.ALL;
			return detectChineseCharset(in);
		} catch (IOException e) {
			throw e;
		}
	}
}
最近下载更多
WHY-small  LV15 2022年11月3日
2469095052  LV8 2021年2月2日
xwj123789  LV1 2020年4月1日
fenglin218  LV11 2019年6月21日
二两小面加个蛋  LV10 2019年3月18日
love9971  LV1 2018年12月11日
seedgiid  LV2 2018年3月21日
wangdongchun  LV8 2018年3月12日
keen1066  LV17 2017年12月13日
复制三次胖狗  LV7 2017年12月6日
最近浏览更多
whhano  LV2 2023年12月20日
1358849392  LV21 2023年6月6日
WHY-small  LV15 2022年11月3日
nothing 2021年11月22日
暂无贡献等级
a14628909  LV4 2021年5月14日
2469095052  LV8 2021年2月2日
rainylan_er 2020年4月4日
暂无贡献等级
writerdreamer  LV1 2020年4月4日
xwj123789  LV1 2020年4月1日
suhuike 2020年2月19日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友