字节缓冲流
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();}