字节缓冲流

简介

缓冲流是对原原始流进行包装,提高原始流读写数据的性能。提供8KB输入输出缓冲区。 

IO流:缓冲流_输入流

IO流:缓冲流_数组_02

用法

IO流:缓冲流_缓冲流_03

public class BufferedInputStreamTest1 {
    public static void main(String[] args) {
        try {
            // 1. 定义一个字节缓冲输入流包裹原始的字节输入流
            InputStream is = new FileInputStream("io-app2/src/itheima01.txt");
            InputStream bis = new BufferedInputStream(is);

            // 2. 定义一个字节缓冲输出流包裹原始的字节输出流
            OutputStream os = new FileOutputStream("io-app2/src/a01_bak.txt");
            OutputStream bos = new BufferedOutputStream(os);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }

            System.out.println("复制完成!");

            // 关闭流
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

字符缓冲流

8kB(8192)的字符缓冲池,以字符为单位。

IO流:缓冲流_缓冲流_04

方法readLine,读一行

public class BufferedReaderTest2 {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("io-app2\\src\\itheima01.txt");
            BufferedReader br = new BufferedReader(fr);

            String line; // 记住每次读取的一行数据
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            // 关闭流
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

方法newLine,新建一行,也就是换行

原始流、缓冲流的性能分析

使用数组的方法和使用缓冲流来复制文件的效果是差不多的,前提是数组的大小和缓冲桶的大小是一样的。