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";
       }

吐槽:刚开始也是网上找的别人的代码,见了最多是这个代码,然并没有效果!!!
在这里插入图片描述

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>

在这里插入图片描述
手动配置jar包的存放路径。。

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

see you again!

  • 9
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Java中可以使用InputStreamReader和FileInputStream来按指定编码格式读取txt文件。具体实现方法如下: ```java File file = new File("example.txt"); // 文件路径 String charset = "UTF-8"; // 指定编码格式 StringBuilder sb = new StringBuilder(); try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charset); BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { sb.append(line).append(System.lineSeparator()); // 按行读取并添加到StringBuilder中 } } catch (IOException e) { e.printStackTrace(); } String content = sb.toString(); // 读取的文件内容 System.out.println(content); ``` 上述代码中,我们首先创建了一个File对象,指定了要读取的文件路径。然后使用InputStreamReader和FileInputStream来按指定编码格式读取文件,并使用BufferedReader按行读取文件内容,将每行内容添加到StringBuilder中。最后将StringBuilder转换为字符串并输出。 如果要写入指定编码格式的txt文件,可以使用OutputStreamWriter和FileOutputStream。具体实现方法如下: ```java File file = new File("example.txt"); // 文件路径 String charset = "GBK"; // 指定编码格式 try (FileOutputStream fos = new FileOutputStream(file, true); OutputStreamWriter osw = new OutputStreamWriter(fos, charset); BufferedWriter bw = new BufferedWriter(osw)) { bw.write("新加的" + charset + "字符,原来的一行是" + charset + "格式"); bw.newLine(); // 换行 } catch (IOException e) { e.printStackTrace(); } ``` 上述代码中,我们首先创建了一个File对象,指定了要写入的文件路径。然后使用OutputStreamWriter和FileOutputStream来按指定编码格式写入文件,并使用BufferedWriter写入文件内容,最后使用newLine()方法换行。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值