`
toyota2006
  • 浏览: 545852 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

Java 获得文件编码格式

阅读更多
其中用到到3个jar包见附件

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;

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

public class CharacterEnding {

	public static String getFileCharacterEnding(String filePath) {

		File file = new File(filePath);

		return getFileCharacterEnding(file);
	}

	/**
	 * Try to get file character ending.
	 * </p>
	 * <strong>Warning: </strong>use cpDetector to detect file's encoding.
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileCharacterEnding(File file) {

		String fileCharacterEnding = "UTF-8";

		CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
		detector.add(JChardetFacade.getInstance());

		Charset charset = null;

		// File f = new File(filePath);

		try {
			charset = detector.detectCodepage(file.toURL());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (charset != null) {
			fileCharacterEnding = charset.name();
		}

		return fileCharacterEnding;
	}
}
分享到:
评论
6 楼 fally 2011-07-21  
用了基于chardet的cpdetector。
这个东东不错,就是有些GBK文件会解析成韩语,郁闷。。。
do77 写道
用了基于chardet的cpdetector。
这个东东不错,就是有些GBK文件会解析成韩语,郁闷。。。


什么GBK文件被解析成韩语?
能发个具体的文件吗
5 楼 suko 2010-03-18  
不错的东西,我已经引用成功了,谢谢楼主分享。
4 楼 llbb2000go 2009-12-16  
在获取文件内容前,根据编码格式选择input流的charset可以确保取到的内容不是乱码。特别是在同时读取多个不同类型文件时,可以减少硬编码
3 楼 whaosoft 2009-12-06  
这个有什么具体的意义吗
2 楼 do77 2009-12-05  
用了基于chardet的cpdetector。
这个东东不错,就是有些GBK文件会解析成韩语,郁闷。。。
1 楼 lkjust08 2009-12-05  
很好,只不过用了第三方的jar,不知道lz有什么好办法不用第三方的东东就可以获得java文件的编码?期待!!!

相关推荐

Global site tag (gtag.js) - Google Analytics