Java如何获取文本文件的字符编码【UTF-8格式判断改进版】

一、认识字符编码:

1、Java中String的默认编码为UTF-8,可以使用以下语句获取:Charset.defaultCharset();

2、Windows操作系统下,文本文件的默认编码为ANSI,对中文Windows来说即为GBK。例如我们使用记事本程序新建一个文本文档,其默认字符编码即为ANSI。

3、Text文本文档有四种编码选项:ANSI、Unicode(含Unicode Big Endian和Unicode Little Endian)、UTF-8、UTF-16

4、因此我们读取txt文件可能有时候并不知道其编码格式,所以需要用程序动态判断获取txt文件编码。

  • ANSI     :无格式定义,对中文操作系统为GBK或GB2312
  • UTF-8   :前三个字节为:0xE59B9E(UTF-8)、0xEFBBBF(UTF-8含BOM)
  • UTF-16 :前两字节为:0xFEFF
  • Unicode:前两个字节为:0xFFFE

例如,Unicode文档以0xFFFE开头,用程序取出前几个字节并进行判断即可。

5、Java编码与Text文本编码对应关系:

Java中的编码字符串Text编码 字节标志
GBK

ANSI

无格式定义
UTF-8

UTF-8包含两种规格:

UTF-8

UTF-8-BOM

需判断前三个字节:

前三个字节为:0xE59B9E

前三个字节为:0xEFBBBF

UTF-16UTF-16前两个字节为:0xFEFF
UNICODE

Unicode包含两种规格:

1、UCS2 Little Endian

2、UCS2 Big Endian

前两个字节为:0xFFFE

Java读取Text文件,如果编码格式不匹配,就会出现乱码现象。所以读取文本文件的时候需要设置正确字符编码。Text文档编码格式都是写在文件头的,在程序中需要先解析文件的编码格式,获得编码格式后,再以此格式读取文件就不会产生乱码了。

二、举个例子:

有一个文本文件:test.txt

  

测试代码: 

/**
 * 文件名:CharsetCodeTest.java
 * 功能描述:文件字符编码测试
 */

import java.io.*;

public class CharsetCodeTest {
    public static void main(String[] args) throws Exception {
        String filePath = "test.txt";
        String content = readTxt(filePath);
        System.out.println(content);
    }


public static String readTxt(String path) {
        StringBuilder content = new StringBuilder("");
        try {
            String fileCharsetName = getFileCharsetName(path);
            System.out.println("文件的编码格式为:"+fileCharsetName);

            InputStream is = new FileInputStream(path);
            InputStreamReader isr = new InputStreamReader(is, fileCharsetName);
            BufferedReader br = new BufferedReader(isr);

            String str = "";
            boolean isFirst = true;
            while (null != (str = br.readLine())) {
                if (!isFirst)
                    content.append(System.lineSeparator());
                    //System.getProperty("line.separator");
                else
                    isFirst = false;
                content.append(str);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("读取文件:" + path + "失败!");
        }
        return content.toString();
    }


    public static String getFileCharsetName(String fileName) throws IOException {
        InputStream inputStream = new FileInputStream(fileName);
        byte[] head = new byte[3];
        inputStream.read(head);

        String charsetName = "GBK";//或GB2312,即ANSI
        if (head[0] == -1 && head[1] == -2 ) //0xFFFE
            charsetName = "UTF-16";
        else if (head[0] == -2 && head[1] == -1 ) //0xFEFF
            charsetName = "Unicode";//包含两种编码格式:UCS2-Big-Endian和UCS2-Little-Endian
        else if(head[0]==-27 && head[1]==-101 && head[2] ==-98)
            charsetName = "UTF-8"; //UTF-8(不含BOM)
        else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
            charsetName = "UTF-8"; //UTF-8-BOM

        inputStream.close();

        //System.out.println(code);
        return charsetName;
    }
}

运行结果:

 

 

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值