代码编织梦想


import java.io.FileInputStream;
import java.io.IOException;

/*
演示FileInputStream的使用(字节输入流)
 */
public class FileInputStreamCls {
    public static void main(String[] args) {
        readFile02();//创建FileInputStream对象,若有中文就会乱码
    }

    //使用read()
    public static void readFile01(){
        String filePath = "d:\\hello.txt";
        FileInputStream fileInputStream = null;
        int readData = 0;
        try {
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            while((readData = fileInputStream.read()) != -1){
                System.out.print((char)readData);
            }
            //从该输入流读取一个字节。如果没有输入可以读取,此方法将被阻止,然后返回-1
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //使用read(byte[] b)读取文件提高效率
    public static void readFile02(){
        String filePath = "d:\\hello.txt";
        FileInputStream fileInputStream = null;
        int readLen = 0;
        //定义一个字节数组
        byte[] buf = new byte[8];
        try {
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            while((readLen = fileInputStream.read(buf)) != -1){
                System.out.print(new String(buf,0,readLen));//显示
            }
            //从该输入流读取一个字节。如果没有输入可以读取,此方法将被阻止,然后返回-1
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/chen_y09/article/details/129676606