字节缓冲流
- 原理:底层自带了长度为**8192字节数组(8kb)**的缓冲区提高性能
构造方法
| 方法名称 | 说明 |
|---|---|
| public BufferedInputStream(InputStream is) | 把基本流包装成高级流,提高读取数据的性能 |
| public BufferedInputStream(InputStream is, int size) | 指定缓冲区的大小 |
| public BufferedOutputStream(OutputStream os) | 把基本流包装成高级流,提高写出数据的性能 |
| public BufferedOutputStream(OutputStream os, int size) | 指定缓冲区的大小 |
- 续写开关要写到基本流中,因为真正在工作的是基本流
- 源码
private static int DEFAULT_BUFFER_SIZE = 8192;
public BufferedInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
public BufferedInputStream(InputStream in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
public BuferedOtuputStream(OutputStream out) {
this(out, 8192);
}
public BuferedOtuputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
使用
- 利用字节缓冲流拷贝文件 (一次读写一个字节)
BufferedInputSteam bis = new BufferedInputStream(new FileInputStream("myio\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOuputStream("myio\\b.txt"));
int b;
while((b = bis.read()) != -1) {
bos.write(b);
}
bos.close();
bis.close();
-
close方法在底层都对基本流进行了关闭操作,因此无需再对基本流进行手动关闭操作
-
利用字节缓冲流拷贝文件 (一次读写一个字节数组)
BufferedInputSteam bis = new BufferedInputStream(new FileInputStream("myio\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOuputStream("myio\\b.txt"));
byte[] bytes = new byte[1024];
int len;
while((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.close();
bis.close();