相较于没有缓冲区的的字符输入流,再一个比较大的文件,视频图片读取和输出的时间上带缓冲区的更快捷,更节约时间。
-
字节缓冲流介绍
-
lBufferOutputStream:该类实现缓冲输出流.通过设置这样的输出流,应用程序可以向底层输出流写入字节,而不必为写入的每个字节导致底层系统的调用
-
lBufferedInputStream:创建BufferedInputStream将创建一个内部缓冲区数组.当从流中读取或跳过字节时,内部缓冲区将根据需要从所包含的输入流中重新填充,一次很多
-
public class BufferedStreamDemo { public static void main(String[] args) { byteWriter(); byteReader(); } private static void byteReader() { File file = new File("F:/test.txt"); try { InputStream in = new FileInputStream(file); // 构造一个字节缓冲流 BufferedInputStream bis = new BufferedInputStream(in); byte[] flush = new byte[1024]; int len = -1; while ((len = bis.read(flush)) != -1) { System.out.println(new String(flush, 0, len)); } bis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }// byteReader private static void byteWriter() { File file = new File("F:/test.txt"); try { OutputStream out = new FileOutputStream(file, true); BufferedOutputStream bos = new BufferedOutputStream(out); String info = "你爱Java吗?"; bos.write(info.getBytes()); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }// byteWriter }
-
把一个文件中的图片复制到另一个文件中
-
//从一个文件里复制图片到另一个文件 public class demo4 { public static void main(String[] args) throws IOException { //读取路径 BufferedInputStream bis=new BufferedInputStream(new FileInputStream(new File("D:\\笔记\\5.jpg"))); //录入路径 BufferedOutputStream boS=new BufferedOutputStream(new FileOutputStream(new File("D:\\aaa\\1.jpg"))); //设置一次缓冲的大小 byte[] buf=new byte[4*1024]; int len; //循环读取当没有了读取不到时java规定返回-1 while((len=bis.read(buf))!=-1) { //录入 boS.write(buf,0,len); } //释放流 bis.close(); boS.close(); } }
-
把一个视频从一个txt文件中录入到另一个文件中
-
public class Demo3 { public static void main(String[] args) throws IOException { //1.创建对应的缓冲字节输入流和缓冲字节输出流对象 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\wangbo\\Desktop\\zz2115\\day21\\video\\2字节输入流的入门案例.mp4"))); //从内存中写入到一个文件中 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("c:/aaa/1.mp4"))); //2.准备一个字节数组缓冲区数组 byte[] buf = new byte[1024 * 4]; int length = -1; //bis.read(buf)) 是从磁盘里面写入到内存 while ((length = bis.read(buf))!= -1) { //从内存中写入磁盘里面 //循环一次写 4096字 bos.write(buf, 0, length); } //关闭流 bos.close(); bis.close();
-