java IO流: 字节输入流 FileInputStream类

字节输入流 InputStream类

  • 此抽象类是表示字节输入流的所有类的超类,定义了一些子类共性的成员方法
  • int read() :从输入流中读取数据的下一个字节。
    • 读取文件中的一个字节并返回,并把指针向后移一位,读取到文件的末尾返回-1
  • int read(byte[] b) :从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
  • void close() :关闭此输入流并释放与该流关联的所有系统资源。

子类 java.io.FileInputStream

  • 文件字节输入流

  • 把硬盘文件中的数据读取到内存中使用

  • 写入数据的原理(硬盘-->内存)

    • java程序→JVM→OS(操作系统)→OS读取数据的方法→读取文件
  • 字节输入流的使用步骤:

    1. 创建一个FileInputStream对象,构造方法中绑定要读取的数据源
    2. 调用FileInputStream对象中的方法read,读取文件
    3. 释放资源

构造方法

  • FileInputStream(File file) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。

  • FileInputStream(String name) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。

  • 作用:

    • 创建一个FileInputStream对象
    • 把FileInputStream对象指定向构造方法中要读取的文件

public class Demo02 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis=new FileInputStream("D:\\document\\code\\xuexi\\java\\aaa\\a.txt");
        int len=0;
        while ((len=fis.read())!=-1){
            System.out.print((char)len);
        }
        fis.close();
    }
}
//结果
//aa
//bb
//cc

字节输入流一次读取多个字节的方法

  • int read(byte[] b)方法:从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中
    • 数组b的作用:缓冲作用,存储每次读取到的多个字节,数组的长度一般定义未1024(1KB)或1024的整数倍
    • 返回值:每次读取的有效字节个数

读取原理:

public class Demo02 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis=new FileInputStream("D:\\document\\code\\xuexi\\java\\aaa\\a.txt");
        byte[] bytes=new byte[1024];
        int len = 0;
        while ((len=fis.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }
        fis.close();
    }
}




字节流练习: 文件复制

  • 复制原理:一读一写
public class Demo {
    public static void main(String[] args) throws IOException {
        //字节输入流,读取
        FileInputStream fis=new FileInputStream("D:\\document\\code\\xuexi\\java\\aaa\\a.txt");
        //字节输出流,写入
        FileOutputStream fos=new FileOutputStream("D:\\document\\code\\xuexi\\java\\aaa\\b.txt");
        //一次读取一个字节写入一个字节方式
        int len=0;
        byte[] bytes=new byte[1024];
        while ((len=fis.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }
        //先关闭写的,后关闭读的
        fos.close();
        fis.close();
    }
}

posted @ 2021-01-06 17:32  迪迦是真的  阅读(139)  评论(0)    收藏  举报
//复制代码按钮 //代码行号 //评论