1字节缓冲区流
1.1 字节缓冲流概述
-
字节缓冲流:
- BufferOutputStream:缓冲输出流
- BufferedInputStream:缓冲输入流
-
构造方法:
- 字节缓冲输出流:BufferedOutputStream(OutputStream out)
- 字节缓冲输入流:BufferedInputStream(InputStream in)
-
为什么构造方法需要的是字节流,而不是具体的文件或者路径呢?
- 字节缓冲流仅仅提供缓冲区,不具备读写功能 , 而真正的读写数据还得依靠基本的字节流对象进行操作
1.2 字节缓冲流案例
public class BufferedStreamDemo1 {public static void main(String[] args) throws IOException {// 创建高效的字节输入流对象// 在底层会创建一个长度为8192的数组BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\Apache24\\htdocs\\brawlive\\site\\upload\\images\\202203\\29\\1648532403_284454_max.jpg"));// 创建高效的字节输出流// 在底层会创建一个长度为8192的数组BufferedOutputStream bos= new BufferedOutputStream(new FileOutputStream("copy2.jpg"));int by;while ((by=bis.read())!=-1){bos.write(by);}//释资资源bis.close();bos.close();}
}
1.2 一次读一个字节和写一个字节原理
package javaio.buffer.demo1;import java.io.*;/*需求:把“11.mp4”复制到模块目录下的“copy.mp4” , 使用四种复制文件的方式 , 打印所花费的时间四种方式:1 基本的字节流一次读写一个字节 : 花费的时间为:1245124毫秒2 基本的字节流一次读写一个字节数组 : 花费的时间为:1245毫秒3 缓冲流一次读写一个字节 : 花费的时间为:3605毫秒4 缓冲流一次读写一个字节数组 : 花费的时间为:280毫秒*/
public class BufferedStreamDemo2 {public static void main(String[] args) throws IOException {long startTime = System.currentTimeMillis();method4();long endTime = System.currentTimeMillis();System.out.println("花费的时间为:" + (endTime - startTime) + "毫秒");}// 4 缓冲流一次读写一个字节数组private static void method4() throws IOException {// 创建高效的字节输入流BufferedInputStream bis=new BufferedInputStream(new FileInputStream("E:\\11.mp4"));// 创建高效的字节输出流BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("copy.mp4"));// 一次读写一个字节数组byte[] bys = new byte[1024];int len;// 每次真实读到数据的个数while ((len=bis.read(bys))!=-1){bos.write(bys,0,len);}//释放资源bis.close();bos.close();}// 3 缓冲流一次读写一个字节private static void method3() throws IOException {// 创建高效的字节输入流BufferedInputStream bis=new BufferedInputStream(new FileInputStream("E:\\11.mp4"));// 创建高效的字节输出流BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("copy.mp4"));// 一次读写一个字节int by;while ((by = bis.read()) != -1) {bos.write(by);}// 释放资源bis.close();bos.close();}// 2 基本的字节流一次读写一个字节数组private static void method2() throws IOException {// 创建基本的字节输入流对象FileInputStream fis = new FileInputStream("E:\\11.mp4");// 创建基本的字节输出流对象FileOutputStream fos = new FileOutputStream("copy.mp4");// 一次读写一个字节数组byte[] bys = new byte[1024];int len;// 每次真实读到数据的个数while ((len=fis.read(bys))!=-1){fos.write(bys,0,len);}fis.close();fos.close();}private static void method1() throws IOException {// 创建基本的字节输入流对象FileInputStream fis = new FileInputStream("E:\\11.mp4");// 创建基本的字节输出流对象FileOutputStream fos = new FileOutputStream("copy.mp4");//一次读一个字节int by;while ((by=fis.read())!=-1){fos.write(by);}//释放资源fis.close();fos.close();}
}