目录

java实现获取文件编码格式,经常用于读取文件内容

目录

java实现获取文件编码格式,经常用于读取文件内容。

1.使用java 语言IO流方式获取文档里面时,由于文档的不同编码方式要采用不同的字符集

eg:如下代码,需要我们用对应文件编码去读取。

   InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"utf-8");//file为文件对象
   reader = new BufferedReader(isr);
   String tempString = null;
   int line = 1;
   while ((tempString = reader.readLine()) != null) { // 一次读入一行,直到读入null为文件结束
        System.out.println("line " + line + ": " + tempString);
              //localBody=localBody+tempString+"\n";
       }

吐槽:刚开始也是网上找的别人的代码,见了最多是这个代码,然并没有效果!!!

https://i-blog.csdnimg.cn/blog_migrate/350fa186cf25e4801e7223ad86bb7238.png

2.常用的文件编码为UTF-8、GBK、ASCII等。获取文件编码格式的java代码实现如下:( 目前个人只测试并使用了UTF-8、GBK、ASCII三种可行,其他格式能否识别不确定。用到的jar包detector放在下面地址!

try {
       bianMa=getFileCharsetName(file);//调用识别编码格式的逻辑
       System.out.println("编码格式为:"+bianMa);
     } catch (Exception e) {
        e.printStackTrace();
 }
     /** 获得文件编码
	 * @param file
	 * @return
      * @throws Exception
	 */

public static String getFileCharsetName(File file) throws Exception {
CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
detector.add(new ParsingDetector(false));
detector.add(JChardetFacade.getInstance());
detector.add(ASCIIDetector.getInstance());
detector.add(UnicodeDetector.getInstance());
Charset charset = null;
try {
charset = detector.detectCodepage(file.toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
String charsetName = "GBK";
if (charset != null) {
if (charset.name().equals("US-ASCII")) {
charsetName = "ISO_8859_1";
} else if (charset.name().startsWith("UTF")) {
charsetName = charset.name();// 例如:UTF-8,UTF-16BE.
}else if(charset.name().equals("GB2312")){
charsetName="GBK";
}
}
return charsetName;//返回最终的编码格式
}   

引入依赖:

<!-- 获取文件编码-->
<dependency>
<groupId>cpdetector</groupId>
<artifactId>cpdetector</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>cpdetector</groupId>
<artifactId>antlr</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>cpdetector</groupId>
<artifactId>chardet</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>cpdetector</groupId>
<artifactId>jargs</artifactId>
<version>1.0</version>
</dependency>

https://i-blog.csdnimg.cn/blog_migrate/a17dc82c1c85756bf30565a93c0f9ed7.png

手动配置 jar 包的存放路径。。

detector 包获取链接:https://pan.baidu.com/s/1fUahdV4TyWa9TQrc0ahouQ

提取码:wj5p

see you again!