Java 获得文件编码

package cn.net.badboy.subtitlesystem.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
	 */
	public static String getFileEncoding(File file){
		try{
			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 = detector.detectCodepage(file.toURI().toURL());
			if (charset!=null) {
				if (charset.name().equalsIgnoreCase("windows-1252")) {
					return "Unicode";
				}
				return charset.name();
			}
			return "UTF-8";
		}catch(Exception e){
			e.printStackTrace();
			return "UTF-8";
		}
	}
}



需要用到这个内裤:
http://cpdetector.sourceforge.net/

你可能感兴趣的:(java,.net,windows)