java实现文件编码监测(转)

 chardet是mozilla自动字符集探测算法代码的java移植。这个算法的最初作者是frank Tang,C++源代码在http://lxr.mozilla.org/mozilla/source/intl/chardet/,可以从http://www.mozilla.org/projects/intl/chardet.html 得到更多关于这个算法的信息。

 

java实现文件编码监测

最近在做一个文档的翻译项目,可文档的编码不知道,听头疼的。尝试了很多方法最后发现JCharDet这个工具可以轻松解决这个问题。于是作此笔记希望日后提醒自己以及帮助又需要的人。

package com.uujava.mbfy.test;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
/**********************************************
 * 	Maven
 * 	<!-- 用于文件编码检查 -->
 *		<dependency>
 *			<groupId>net.sourceforge.jchardet</groupId>
 *			<artifactId>jchardet</artifactId>
 *			<version>1.0</version>
 *		</dependency>
 * *********************************************/
/**
 * 借助JCharDet获取文件字符集 JCharDet
 * 是mozilla自动字符集探测算法代码的java移植,其官方主页为:
 * http://jchardet.sourceforge.net/
 */
public class FileCharsetDetector {

	private boolean found = false;

	/**
	 * 如果完全匹配某个字符集检测算法, 则该属性保存该字符集的名称.
	 * 否则(如二进制文件)其值就为默认值 null, 这时应当查询属性
	 */
	private String encoding = null;

	public static void main(String[] argv) throws Exception {

		System.out
				.println("文件编码:"
						+ new FileCharsetDetector()
								.guestFileEncoding("/home/k/Documents/test/azmind_7_xh/azmind_7_xh/路由管理.txt"));
	}

	/**
	 * 传入一个文件(File)对象,检查文件编码
	 *
	 * @param file
	 *            File对象实例
	 * @return 文件编码,若无,则返回null
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public String guestFileEncoding(File file) throws FileNotFoundException,
			IOException {
		return geestFileEncoding(file, new nsDetector());
	}

	/**
	 * 获取文件的编码
	 *
	 * @param file
	 *            File对象实例
	 * @param languageHint
	 *            语言提示区域代码 eg:1 : Japanese; 2 : Chinese; 3 : Simplified Chinese;
	 *            4 : Traditional Chinese; 5 : Korean; 6 : Dont know (default)
	 * @return 文件编码,eg:UTF-8,GBK,GB2312形式,若无,则返回null
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public String guestFileEncoding(File file, int languageHint)
			throws FileNotFoundException, IOException {
		return geestFileEncoding(file, new nsDetector(languageHint));
	}

	/**
	 * 获取文件的编码
	 *
	 * @param path
	 *            文件路径
	 * @return 文件编码,eg:UTF-8,GBK,GB2312形式,若无,则返回null
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public String guestFileEncoding(String path) throws FileNotFoundException,
			IOException {
		return guestFileEncoding(new File(path));
	}

	/**
	 * 获取文件的编码
	 *
	 * @param path
	 *            文件路径
	 * @param languageHint
	 *            语言提示区域代码 eg:1 : Japanese; 2 : Chinese; 3 : Simplified Chinese;
	 *            4 : Traditional Chinese; 5 : Korean; 6 : Dont know (default)
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public String guestFileEncoding(String path, int languageHint)
			throws FileNotFoundException, IOException {
		return guestFileEncoding(new File(path), languageHint);
	}

	/**
	 * 获取文件的编码
	 *
	 * @param file
	 * @param det
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private String geestFileEncoding(File file, nsDetector det)
			throws FileNotFoundException, IOException {
		// 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;
				encoding = charset;
			}
		});

		BufferedInputStream imp = new BufferedInputStream(new FileInputStream(file));

		byte[] buf = new byte[1024];
		int len;
		boolean done = false;
		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 && !done)
				done = det.DoIt(buf, len, false);
		}
		det.DataEnd();

		if (isAscii) {
			encoding = "ASCII";
			found = true;
		}

		if (!found) {
			String prob[] = det.getProbableCharsets();
			if (prob.length > 0) {
				// 在没有发现情况下,则取第一个可能的编码
				encoding = prob[0];
			} else {
				return null;
			}
		}
		return encoding;
	}
}http://www.cnblogs.com/mxcy/p/4008342.html
时间: 2024-05-22 13:20:42

java实现文件编码监测(转)的相关文章

JAVA判断文件编码类型

[本文转载于JAVA判断文件编码类型] java读取文件,处理过程中,可能因为文件的编码问题导致了中文乱码.有时需要将UTF-8的改为ANSI的编码.以下代码就可以判断文件是什么编码方式. 主要jar包:cpdetector.jar  下载地址http://cpdetector.sourceforge.net/  同时还需jchardet-1.0.jar这个包,否则detector.add(cpdetector.io.JChardetFacade.getInstance());  会报错: 下载

JAVA探测文件编码

我们在做一些类似文件上传的功能时,用户上传的文件编码,我们是无法控制的,这是我们就需要对文件的编码进行探测. 示例代码如下: import info.monitorenter.cpdetector.io.ASCIIDetector; import info.monitorenter.cpdetector.io.CodepageDetectorProxy; import info.monitorenter.cpdetector.io.JChardetFacade; import info.moni

Java IO文件编码转换实现代码_java

对IO操作真心不是很懂...对编码.乱码也是一知半解...今天遇到了一个需求,要求将一个文件进行编码转换,并且返回编码后的字符串,如原本的GBK编码,转换为UTF-8 其中这个BytesEncodingDetect 类就不贴了.主要用了里面的获取文件编码格式. 刚开始试了直接在源文件修改编码方式,采用URLEncoder和URLDecoder进行转换,却迟迟不行.出现了中文奇数最后一个字乱码 百度找了解决方法,都未果,只好采用我的思路是:先读取源文件的内容,存放到StringBuffer里面,然

Java判断文件编码,转换编码及解决中文乱码

 代码如下 复制代码 try {    File file = new File(lrcPath);      // 获取原始文件编码    CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();    detector.add(JChardetFacade.getInstance());    Charset charset = null;    charset = detector.detectCodepag

用java从文件中读取utf-8编码,并将其编码后输出对应的字符

问题描述 用java从文件中读取utf-8编码,并将其编码后输出对应的字符 文本文件(.txt)中有一行utf-8编码,例如:u4E2Du534Eu4EBAu6C11u5171u548Cu56FD,怎么样才能利用java将其从文件中读取出来以后进行编码,并将其对应的字符输出来? 解决方案 楼主搞混了UTF-8和Unicode编码了,你的问题中给出的是Unicode编码例子,Unicode的是以反斜杠+u开头的,而UTF-8是以%开头的. UTF-8的操作直接使用URLEncoder这个类来转换,

java按指定编码写入和读取文件内容的类分享_java

可以指定编码如:utf-8来写入和读取文件.如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题. 如何识别文件编码请参考:java自动根据文件内容的编码来读取避免乱码 复制代码 代码如下: package com.zuidaima.util; import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputS

(透彻)java String.getBytes()编码问题

String.getBytes()的问题 String 的getBytes()方法是得到一个字串的字节数组,这是众所周知的.但特别要注意的是,本方法将返回该操作系统默认的编码格式的字节数组.如果你在使 用这个方法时不考虑到这一点,你会发现在一个平台上运行良好的系统,放到另外一台机器后会产生意想不到的问题.比如下面的程序: class TestCharset {  public static void main(String[] args) {  new TestCharset().execute

java中文乱码解决之道(五)—–java是如何编码解码的

编码&解码 1:I/O操作 2:内存 3:数据库 4:javaWeb 下面主要介绍前面两种场景,数据库部分只要设置正确编码格式就不会有什么问题,javaWeb场景过多需要了解URL.get.POST的编码,servlet的解码,所以javaWeb场景下节LZ介绍. I/O操作 在前面LZ就提过乱码问题无非就是转码过程中编码格式的不统一产生的,比如编码时采用UTF-8,解码采用GBK,但最根本的原因是字符到字节或者字节到字符的转换出问题了,而这中情况的转换最主要的场景就是I/O操作的时候.当然I/

eclipse java maven-Eclipse中Java代码的编码问题

问题描述 Eclipse中Java代码的编码问题 Eclipse中使用Maven项目,项目中Java文件不能复制代码,即使可以复制传到另一个电脑乱码,求大神帮忙?用记事本,EditPlus打开也是乱码,传给别人也是乱码,粘贴不了代码,只能在自己Eclipse中打开项目,现在都不敢用git提交,该如何解决. 解决方案 找到首选项,常规,看一下你的工作组空间的代码编码配置有没有问题 解决方案二: 先使用浏览器,看看本身的编码格式.再来寻找解决方案 解决方案三: Eclipse中编码首选项,工作空间没