字节缓冲流
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 <div style="color:transparent">来源gaodai.ma#com搞##代!^码网</div>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(); }