那些你一直没有搞明白的Java缓冲流细节!

发布时间:2019-11-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了那些你一直没有搞明白的Java缓冲流细节!脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

>>FileOutPutStream继承OutputStream,并不提供flush()方法的重写所以无论内容多少wrITe都会将二进制流直接传递给底层操作系统的I/O,flush无效果。而Buffered系列输入输出流函数单从Buffered这个单词就可以看出他们是使用缓冲区的。
  应用程序每次IO都要和设备进行通信,效率很低,因此缓冲区为了提高效率,当写入设备时,先写入缓冲区,每次等到缓冲区满了时,就将数据一次性整体写入设备,避免了每一个数据都和IO进行一次交互,IO交互消耗太大。

使用flush()和不使用flush()效果对比

不使用flush()

       String s = "Hello World";         try {             // create a new stream at sPEcified file             PRintWriter pw = new PrintWriter(System.out);             // write the string in the file             pw.write(s); //            // flush the writer //            pw.flush();         } catch (Exception ex) {             ex.printStackTrace();         }  输出:

buffer没有满,输出为空。

使用buffer()

        String s = "Hello World";         try {             // create a new stream at specified file             PrintWriter pw = new PrintWriter(System.out);             // write the string in the file             pw.write(s);             // flush the writer            pw.flush();         } catch (Exception ex) {             ex.printStackTrace();         }

得到期望的输出结果。

解析

close()和flush()作用有交集!

public static void main(String[] args) {         BufferedWriter fw =null;         try {             fw =  new BufferedWriter(new FileWriter("e:\test.txt"));             fw.write("wo shi lucky girl.");             //fw.flush();             fw.close();         } catch (Exception e) {             e.printStackTrace();         }     }  //fw.flush();这句有和无并不影响输出结果,不太明白词句是否必要?

因为close的时候,会把你没flush掉的一起flush掉。
缓冲区中的数据保存直到缓冲区满后才写出,也可以使用flush方法将缓冲区中的数据强制写出或使用close()方法关闭流,关闭流之前,缓冲输出流将缓冲区数据一次性写出。在这个例子中,flash()和close()都使数据强制写出,所以两种结果是一样的,如果都不写的话,会发现不能成功写出

Java默认缓冲区大小是多少?

默认缓冲去大小8192字节。

实验

  char[] array  = new char[8192];         Arrays.fill(array,'s');         PrintWriter pw = new PrintWriter(System.out);         pw.write(array);   output:     
  char[] array  = new char[8193];         Arrays.fill(array,'s');         PrintWriter pw = new PrintWriter(System.out);         pw.write(array);   output:     ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss..一共8193个s...sssssssssssssssssssssssssssssssssssssssssssssss

当设置数组长度为8192时没有输出,设置8193时有输出。

经典问题

数据重复问题

《重点看答案解析!!!》

脚本宝典总结

以上是脚本宝典为你收集整理的那些你一直没有搞明白的Java缓冲流细节!全部内容,希望文章能够帮你解决那些你一直没有搞明白的Java缓冲流细节!所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。