获取文件的编码

package com.jingwei.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;

/**
 * 文件操作工具类
 */
public class FileUtil {
	/**
	 * 获取文件的编码格式
	 * @param file	文件对象
	 * @return		编码格式名称
	 */
	@SuppressWarnings("deprecation")
	public static String getChartsetName(File file) {
		String chartsetName = null;
    	//获取文件编码格式
    	CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
    	detector.add(new ParsingDetector(false));
    	detector.add(JChardetFacade.getInstance());
    	detector.add(ASCIIDetector.getInstance());
    	detector.add(UnicodeDetector.getInstance());
    	java.nio.charset.Charset charset = null;
    	try {
    		if (file != null) {
    			 charset = detector.detectCodepage(file.toURL());
    		}
    	} catch (Exception ex) {
    	    ex.printStackTrace();
    	}
    	if (charset != null) {
    	    chartsetName=charset.name();
    	} else {
    	    chartsetName="UTF-8";
    	}
    	return chartsetName;
	}
	
	public static void main(String[] args) {
		File file = new File("E:\\自定义.xls");
		String chartsetName = getChartsetName(file);
		System.out.println(chartsetName);
	}
}

 

posted @ 2017-09-12 10:32  半生戎马,共话桑麻、  阅读(866)  评论(0)    收藏  举报
levels of contents