基本流:FileInputStream、FileOutputStream、FileReader、FileWriter
对基本流进行封装,加上缓冲区变成缓冲流,提高读写的效率。
缓冲流:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter
BufferedInputStream字节缓冲输入流
BufferedOutputStream字节缓冲输出流
原理:底层自带了长度为8192(8KB)的缓冲区提高性能。
构造方法:
public BufferedInputStream(InputStream is)
把基本流包装成高级流,提高了读取数据的性能。
public BufferedOutputStream(OutputStream os)
把基本流包装成高级流,提高了写出数据的性能。
缓冲流本身不能直接读取数据,也不能把数据直接写出到文件中。在创建对象的时候,缓冲流需要关联基本流,真正读取数据写出数据的还是基本流,缓冲流只是提高了效率。
练习:
利用字节缓冲流拷贝文件 (一次操作一个字节)
public class BufferedStreamDemo1 {
public static void main(String[] args) throws IOException {
/*
* 需求:
* 利用字节缓冲流拷贝文件
*
* 字节缓冲输入流的构造方法:
* public BufferedInputStream(InputStream is)
*
* 字节缓冲输出流的构造方法:
* public BufferedOutputStream(OutputStream os)
*
* */
//1.创建缓冲流的对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("myio\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myio\\a.txt"));
//2.循环读取并写到目的地
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
//3.释放资源
bos.close();
bis.close();
}
}
利用字节缓冲流拷贝文件(一次操作一个字节数组)
public class BufferedStreamDemo2 {
public static void main(String[] args) throws IOException {
/*
* 需求:
* 利用字节缓冲流拷贝文件
*
* 字节缓冲输入流的构造方法:
* public BufferedInputStream(InputStream is)
*
* 字节缓冲输出流的构造方法:
* public BufferedOutputStream(OutputStream os)
*
* */
//1.创建缓冲流的对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("myio\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myio\\copy2.txt"));
//2.拷贝(一次读写多个字节)
byte[] bytes = new byte[1024];
int len;//表示:当前操作的字节个数
while((len = bis.read(bytes)) != -1){//把读取到的数据放到数组当中,并返回int型的整数
bos.write(bytes,0,len);//把数组当中0~len个字节写出
}
//3.释放资源
bos.close();
bis.close();
}
}
1、缓冲区在哪里?
public BufferedInputStream(InputStream in) { this(in, 8192);//底层源码:缓冲区大小8192字节 //把字节输入流和8192传递给本地的其他构造方法 }
public BufferedInputStream(InputStream in, int size) { super(in); this.markpos = -1; if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } else { this.initialSize = size; if (this.getClass() == BufferedInputStream.class) { this.lock = InternalLock.newLockOrNull(); this.buf = EMPTY; } else { this.lock = null; this.buf = new byte[size];//缓冲区 } } }
2、为什么释放资源不需要关基础流?
底层代码有,会自动关闭基本流。