论坛首页 入门技术论坛

Java 获得文件编码格式

浏览 7965 次
精华帖 (0) :: 良好帖 (2) :: 新手帖 (2) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-12-03   最后修改:2009-12-03
其中用到到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;
	}
}
   发表时间:2009-12-05  
很好,只不过用了第三方的jar,不知道lz有什么好办法不用第三方的东东就可以获得java文件的编码?期待!!!
0 请登录后投票
   发表时间:2009-12-05  
用了基于chardet的cpdetector。
这个东东不错,就是有些GBK文件会解析成韩语,郁闷。。。
0 请登录后投票
   发表时间:2009-12-06  
这个有什么具体的意义吗
0 请登录后投票
   发表时间:2009-12-16  
在获取文件内容前,根据编码格式选择input流的charset可以确保取到的内容不是乱码。特别是在同时读取多个不同类型文件时,可以减少硬编码
0 请登录后投票
   发表时间:2010-03-18  
不错的东西,我已经引用成功了,谢谢楼主分享。
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics