收藏 java 如何判断txt的编码字符集

package com.golden.nacecsns.weblayer.action.web.login;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class eee {
    public static void main(String[] args) {
        try {
            String charset = getCharset(new File("c:\\2.txt"));
            System.out.println(charset);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
     public static String toHex(byte[] byteArray) {
            int i;
            StringBuffer buf = new StringBuffer("");
            int len = byteArray.length;
            for (int offset = 0; offset < len; offset++) {
                i = byteArray[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString().toUpperCase();
        }
      private static String getCharset(File fileName) throws IOException {
            BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
            byte[] b = new byte[10];
            bin.read(b, 0, b.length);
            String first = toHex(b);
     //这里可以看到各种编码的前几个字符是什么,gbk编码前面没有多余的
            String code = null;
            if (first.startsWith("EFBBBF")) {
                code = "UTF-8";
            } else if (first.startsWith("FEFF00")) {
                code = "UTF-16BE";
            } else if (first.startsWith("FFFE")) {
                code = "Unicode";
            } else if (first.startsWith("FFFE")) {
                code = "Unicode";
            } else {
                code = "GBK";
            }
            return code;
        }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值