Bootstrap

JavaSE 面向对象程序设计进阶 IO流练习 字节缓冲流 字符缓冲流 底层原理

目录

字节缓冲流

字节缓冲流底层原理

字符缓冲流

字节缓冲流

刚刚学习的四个流是基本流

对四个基本流进行封装,添加了新的功能,叫做缓冲流

底层自带长度为8192的缓冲区

import java.io.*;

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

        //创建字节缓冲流的对象
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream("untitled\\a.txt"));
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("untitled\\b.txt"));

        //循环读取并写到目的地 一次操作一个字节
        int b;
        while((b=bis.read())!=-1)
            bos.write(b);

        bos.close();
        bis.close();
    }
}

默认的缓存区 长度为8192

import java.io.*;

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

        //创建字节缓冲流的对象
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream("untitled\\a.txt"));
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("untitled\\b.txt"));

        //循环读取并写到目的地 一次操作多个字节
        byte[] bytes=new byte[1024];
        int len;
        while((len=bis.read(bytes))!=-1)
            bos.write(bytes,0,len);
        
        //释放资源
        bos.close();
        bis.close();
    }
}

字节缓冲流底层原理

两个缓冲区

循环重复一直到读取完文件到末尾

内存中的读取速度是非常快的

字符缓冲流

import java.io.*;

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

        //创建字符缓冲输入流的对象
        BufferedReader br=new BufferedReader(new FileReader("untitled\\a.txt"));

        String line;
        while((line=br.readLine())!=null)
            System.out.println(line);


        //创建字符缓存输出流的对象
        BufferedWriter bw=new BufferedWriter(new FileWriter("untitled\\b.txt",true));
        bw.write("你好");
        bw.newLine();

        
        //释放资源
        bw.close();
        br.close();
    }
}

个人号推广

博客主页

朱道阳-CSDN博客

Web后端开发

https://blog.csdn.net/qq_30500575/category_12624592.html?spm=1001.2014.3001.5482

Web前端开发

https://blog.csdn.net/qq_30500575/category_12642989.html?spm=1001.2014.3001.5482

数据库开发

https://blog.csdn.net/qq_30500575/category_12651993.html?spm=1001.2014.3001.5482

项目实战

https://blog.csdn.net/qq_30500575/category_12699801.html?spm=1001.2014.3001.5482

算法与数据结构

https://blog.csdn.net/qq_30500575/category_12630954.html?spm=1001.2014.3001.5482

计算机基础

https://blog.csdn.net/qq_30500575/category_12701605.html?spm=1001.2014.3001.5482

回忆录

https://blog.csdn.net/qq_30500575/category_12620276.html?spm=1001.2014.3001.5482

;