基本知识"/>
缓冲流的基本知识
拥有加快读写速度的功能,文件输出流是一次只读一个字节,缓冲输出流其实底层是一次读取一组字节
BufferedOutputstream
FileInputStream fis = new FileInputStream("集体照1.jpg");FileOutputStream fos = new FileOutputStream("集体照3.jpg");int d = -1;long start = System.currentTimeMillis();while((d=fis.read())!=-1){fos.write(d);}long end = System.currentTimeMillis();System.out.println("复制完毕,耗时"+(end-start)+"ms");fos.close();
在用BufferedOutputstream套在fos上面之后
FileInputStream fis = new FileInputStream("集体照1.jpg");BufferedInputStream bis = new BufferedInputStream(fis);FileOutputStream fos = new FileOutputStream("集体照3.jpg");BufferedOutputStream bos = new BufferedOutputStream(fos);int d = -1;long start = System.currentTimeMillis();while((d=bis.read())!=-1){bos.write(d);}long end = System.currentTimeMillis();System.out.println("复制完毕,耗时"+(end-start)+"ms");bos.close();
缓冲流的加速功能显而易见。
但是缓冲流也有个缺点,就是它每次读写都是块读写,这样就可能导致有时候需要读写的内容填不满它的“缓冲区”,但是我们又需要它把未填满的“缓冲区”写完,所以这时候就可以调用它的flush()方法。
FileOutputStream fos = new FileOutputStream("aaa.txt");BufferedOutputStream bos = new BufferedOutputStream(fos);String str = "红尘多可笑,痴情最无聊";bos.write(str.getBytes("gbk"));bos.flush();//需要有即时性的效果就要调用此方法,但是多次调用会降低写的效率System.out.println("写出完毕");bos.close();
flush()方法是要求bos把当前缓存区的内容写出到文件中,但是多次调用会增加实际写出的次数从而降低写的效率,所以也要根据实际情况来调用。
更多推荐
缓冲流的基本知识
发布评论