java中读取UTF-8文件时有时会出现第一行乱码问题

UTF-8文件本身分为带有BOM和NO BOM的文件格式,即用记事本对UTF-8文件打开后再另存为UTF-8时会在文件中插入一个BOM。

从而导致读取时出现乱码。

解决方式

 

 

/**
     * @name UnicodeReader
     * @Date 2010-06-23
     * @param InputStream is :输入流
     * @param String encoding :默认字符集
     * @return InputStreamReader
     *
     */
    protected static InputStreamReader UnicodeReader(InputStream is,
            String encoding) throws IOException
    {

        final int BOM_SIZE = 4;
        byte bom[] = new byte[BOM_SIZE];
        int n, unread;

        if (is == null)
            return null;

        PushbackInputStream internalIn = new PushbackInputStream(is, BOM_SIZE);

        n = internalIn.read(bom, 0, bom.length);

        if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
                && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF))
        {
            encoding = "UTF-32BE";
            unread = n - 4;
        }
        else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
                && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00))
        {
            encoding = "UTF-32LE";
            unread = n - 4;
        }
        else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
                && (bom[2] == (byte) 0xBF))
        {
            encoding = "UTF-8";
            unread = n - 3;
        }
        else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF))
        {
            encoding = "UTF-16BE";
            unread = n - 2;
        }
        else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE))
        {
            encoding = "UTF-16LE";
            unread = n - 2;
        }
        else
        {
            // Unicode BOM mark not found, unread all bytes
            if (encoding.equals(""))
            {
                encoding = "UTF-8";
            }
            unread = n;
        }

        if (unread > 0)
            internalIn.unread(bom, (n - unread), unread);

        return (new InputStreamReader(internalIn, encoding));

    }

 

public static void main(String[] args) throws IOException
    {

        File f = new File("D://G-mybackup//sametime//index.ini");
        FileInputStream in = new FileInputStream(f);
        // 指定读取文件时以UTF-8的格式读取
        BufferedReader br = new BufferedReader(UnicodeReader(in,"UTF-8"));
        String line = br.readLine();
        while (line != null)
        {
            System.out.println(line);
            line = br.readLine();
        }
    }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值