目录

FileInputStream(文件字节输入流)

1. InputStream 常用的子类

2. FileInputStream介绍

2.1 构造方法摘要

2.2 方法摘要

2.3 应用实例:请使用FileInputStream读取 hello.txt 文件,并将文件内容显示到控制台


FileInputStream(文件字节输入流)

1. InputStream 常用的子类

  • FileInputStream:文件字节输入流
  • BufferedInputStream:缓冲字节输入流
  • ObjectInputStream:对象字节输入流

2. FileInputStream介绍

2.1 构造方法摘要

  • FileInputStream(File file):通过打开与实际文件的连接创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
  • FileInputStream(FileDescriptor fdObj):创建 FileInputStream通过使用文件描述符 fdObj ,其表示在文件系统中的现有连接到一个实际的文件。
  • FileInputStream(String name):通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。

2.2 方法摘要

2.3 应用实例:请使用FileInputStream读取 hello.txt 文件,并将文件内容显示到控制台

在D盘新建一个 hello.txt 文件

2.3.1 使用read()方法读取

public class FileInputStream01 {
    public static void main(String[] args) {

    }
    @Test
    public void readFile01(){
        String filePath = "D:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建 FileInputStream 对象,用于读取文件
             fileInputStream = new FileInputStream(filePath);
            //如果返回-1,表示读取完毕
            while ((readData = fileInputStream.read()) != -1){
                //转成char显示
                System.out.print((char)readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}




 2.3.2 使用 read(byte[] b) 方法读取

public class FileInputStream01 {
    public static void main(String[] args) {

    }
    @Test
    public void readFile02(){
        String filePath = "D:\\hello.txt";
        int readlen = 0;
        //字节数组,一次读取8个字节
        byte[] buf = new byte[8];
        FileInputStream fileInputStream = null;
        try {
            //创建 FileInputStream 对象,用于读取文件
             fileInputStream = new FileInputStream(filePath);
            //如果返回-1,表示读取完毕
            //如果读取正常,返回实际读取的字节数
            while ((readlen = fileInputStream.read(buf)) != -1){
                //转成字符串
                System.out.print(new String(buf,0,readlen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐