字节缓冲流
BufferedOutputStream可以向底层输出流写入字节,底层调用次数减少
默认封装大小都是8192
构造方法
//创建字节输出流对象
FileOutputStream fos = new FileOutputStream(name:"myByteStream\\bos.txt");//alt enter抛出异常 IOException
//字节缓冲输出流对象
BufferedOutputStream bos = new BufferedOutputStream(fos);
//上面两行等效替代
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name:"myByteStream\\bos.txt"));
//写数据 靠底层的输出流去做 创建字节输出流对象
bos.write("hello\r\n".getBytes());
bos.write("world\r\n".getBytes());
//释放资源
bos.close();
//读数据 靠底层的输入流去做 创建字节输入流对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(name:"myByteStream\\bos.txt"));
//读数据 一次读取一个字节数据
int by;
while((by = bis.read())!=-1){
sout((char)by);
}
//读数据 一次读取一个字节数组数据
byte[] bys = new byte[1024];
int len;
while((len = bis.read(bys))!=-1){
sout(new String(bys,offset:0,len));
}
//释放资源
bis.close();
案例 复制视频
把"E:\itcast\字节流复制图片.avi"复制到模块目录下的"字节流复制图片.avi"
//记录开始时间
long startTime = System.currentTimeMillis();
//复制视频
method1();//64565毫秒
method2();//107毫秒
method3();//405毫秒
method4();//60毫秒
//记录结束时间
long endTime = System.currentTimeMillis();
sout("共耗时:"+(endTime-startTime)+"毫秒");
//基本字节流一次读取一个字节
public static void method1(){
//数据源
FileInputStream fis = new FileInputStream(name:"E:\\itcast\\字节流复制图片.avi");
//目的地
FileOutputStream fos = new FileOutputStream(name:"myByteStream\\字节流复制图片.avi");
int by;
while((by = fis.read())!=-1){
fos.write(by);
}
fos.close();
fis.close();
}
//基本字节流一次读取一个字节数组
public static void method2(){
//数据源
FileInputStream fis = new FileInputStream(name:"E:\\itcast\\字节流复制图片.avi");
//目的地
FileOutputStream fos = new FileOutputStream(name:"myByteStream\\字节流复制图片.avi");
byte[] bys = new byte[1024];
int len;
while((len = fis.read(bys))!=-1){
fos.write(bys,offset:0,len));
}
fos.close();
fis.close();
}
//字节缓冲流一次读取一个字节
public static void method3(){
//数据源
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(name:"E:\\itcast\\字节流复制图片.avi"));
//目的地
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name:"myByteStream\\字节流复制图片.avi"));
int by;
while((by = bis.read())!=-1){
bos.write(by);
}
bos.close();
bis.close();
}
//字节缓冲流一次读取一个字节数组
public static void method3(){
//数据源
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(name:"E:\\itcast\\字节流复制图片.avi"));
//目的地
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name:"myByteStream\\字节流复制图片.avi"));
byte[] bys = new byte[1024];
int len;
while((len = bis.read(bys))!=-1){
bos.write(bys,offset:0,len));
}
bos.close();
bis.close();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。