一、字节缓冲流(BufferedStream)
1.作用:提高文件拷贝效率
2.其原理是在底层创建了一个默认长度为8192的字节数组
3.注:字节缓冲流不能直接操作文件,需传入字节流,例如:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("myByteStream\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\copy.txt"));
二、代码演示
1.一次只拷贝一个字节:
public class bufferedStreamDemo_01 {
public static void main(String[] args) throws IOException {
//创建一个字节缓冲输入流
//其原理是在底层创建了一个默认长度为8192的字节数组
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("myByteStream\\a.txt"));
//创建一个字节缓冲输出流
//也在底层创建了一个默认长度为8192的字节数组
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\copy.txt"));
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
//关流
bis.close();
bos.close();
}
}
2.一次拷贝一个字节数组:
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("myByteStream\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\copy.txt"));
byte[] bys = new byte[1024];
int len; //表示本次读到的有效字节个数
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
//关流
bis.close();
bos.close();
}