java自动识别用户上传的文本文件编码

经常碰到用户上传的部分数据文本文件乱码问题,又不能限制用户的上传的文件编码格式(这样对客户的要求可能比较高), 只好自己想办法.  找了一部分java获取文件编码的.  

  要么就是识别错误. 要么就是只有一小段的代码,也不说具体引用了什么...我就在这里分享一下吧. 工具类就一个方法. main测试方法我就不写了.

 貌似还不能上传附件...就弄到我的资源里去吧.  

引用了.这两个jar类.

chardet.jar

cpdetector_1.0.10.jar

 

package com.dxx.buscredit.common.util;

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

import java.io.File;
import java.nio.charset.Charset;

public class FileCharsetDetector {

	/**
	 * 利用第三方开源包cpdetector获取文件编码格式.
	 * @param filePath
	 * @return
	 */
	public static String getFileEncode(File file) {
		/**
		 * <pre>
		 * 1、cpDetector内置了一些常用的探测实现类,这些探测实现类的实例可以通过add方法加进来,
		 * 如:ParsingDetector、 JChardetFacade、ASCIIDetector、UnicodeDetector. 
		 * 2、detector按照“谁最先返回非空的探测结果,就以该结果为准”的原则. 
		 * 3、cpDetector是基于统计学原理的,不保证完全正确.
		 * </pre>
		 */
		CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
		
		detector.add(new ParsingDetector(false));
		detector.add(UnicodeDetector.getInstance());
		detector.add(JChardetFacade.getInstance());//内部引用了 chardet.jar的类
		detector.add(ASCIIDetector.getInstance());
		
		Charset charset = null;
		try {
			charset = detector.detectCodepage(file.toURI().toURL());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//默认为GBK
		String charsetName = "GBK";
		if (charset != null) {
			if (charset.name().equals("US-ASCII")) {
				charsetName = "ISO_8859_1";
			} else{
				charsetName = charset.name();
			}
		}
		return charsetName;
	}
}

 

 


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

it夜猫who

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值