java自动识别用户上传的文本文件编码
发布时间:2020-12-15 00:28:49 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 package com.dxx.buscredit.common.util; import info.monitorenter.cpdetector.io.ASCIIDetector; import info.monitorenter.cpdetector.io.Codepage
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 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; } }来自:http://blog.csdn.net/ysola4/article/details/42442357 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |