2021-4-11-1 FileInputStream读取文本文件可以能会乱码

txt

你好,世界!

java,5个byte读一次

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

public class FileInputStreamTest {
    public static void main(String[] args) throws IOException {
        //1. File实例化
        File file = new File("Hello\\src\\io\\hello.txt");

        //2. 流实例化
        FileInputStream fi = new FileInputStream(file);

        //3. 读取文本文件
        byte[] buffer = new byte[5];
        int len;
        while((len = fi.read(buffer)) != -1){
            String str = new String(buffer,0,len);
            System.out.print(str);
        }

        //4. 关闭资源
        fi.close();
    }
}

运行结果
在这里插入图片描述

原因

String默认采用的是utf-8的编码格式。在utf-8里面,中文字占3个Byte,中文字符也占3个Byte。这里我们每次读5个Byte,然后转换为utf-8的编码,5个Byte前面3个Byte就代表了一个中文字,没有问题,但是后面2个Byte呢,它们应该再和后面没读入的1个Byte,共同组成3个Byte,代表一个中文字,但是我们每次读入5个Byte,所以它们被拆分了,所以就出现了乱码。

那我们试试每次读入3个Byte,然后去读入中文内容,看看能不能正确输出

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

public class FileInputStreamTest {
    public static void main(String[] args) throws IOException {
        //1. File实例化
        File file = new File("Hello\\src\\io\\hello.txt");

        //2. 流实例化
        FileInputStream fi = new FileInputStream(file);

        //3. 读取文本文件
        byte[] buffer = new byte[3];
        int len;
        while((len = fi.read(buffer)) != -1){
            String str = new String(buffer,0,len);
            System.out.print(str);
        }

        //4. 关闭资源
        fi.close();
    }
}

在这里插入图片描述


版权声明:本文为quanxiaobai_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。