字节缓冲流
1.输出字节缓冲流:
public static void byteWriter(){ File file = new File("1.txt"); try { OutputStream out = new FileOutputStream(file); //使用缓冲流--构造一个字节缓冲流 BufferedOutputStream bos = new BufferedOutputStream(out); String info = "hah挂失对岸是个"; bos.write(info.getBytes()); //关闭缓冲流 //关闭缓冲流时流的内容就刷新了,或者手动刷新 bos.close(); //关闭缓冲流时已经做过了-----关闭字节输出流 JDK1.7后 // out.close(); } catch (IOException e) { e.printStackTrace(); } }
点击缓冲流的close()方法可以看到如下,使用Try确保字节输出流关闭,然后刷新缓存的流:
点开BufferedOutputStream时,会看到默认缓存为8kb:
每次写入时存储到缓存中的byte数组中,当数组存满时或刷新流时才会真正写入文件,并且缓存下标归零:
2.输入字节缓冲流:
//输入字节缓冲流 public static void byteReader(){ File file = new File("1.txt"); try { InputStream in = new FileInputStream(file); //使用缓冲流--构造一个字节缓冲流 BufferedInputStream bis = new BufferedInputStream(in); byte[] bytes = new byte[1024]; int len = -1; StringBuilder sb = new StringBuilder(); while ((len=bis.read(bytes))!=-1){ sb.append(new String(bytes,0,len)); } System.out.println(sb); //关闭缓冲流 //关闭缓冲流时流的内容就刷新了,或者手动刷新 bis.close(); //关闭缓冲流时已经做过了-----关闭字节输出流 JDK1.7后 // out.close(); } catch (IOException e) { e.printStackTrace(); } }
同样的,字节输入流缓存也是默认8KB,关闭字节输入缓冲流时也会关闭字节输入流,我们点开查看源码可以看到:
使用Try去自动关闭流,以上代码就变成了:
//输入字节缓冲流 public static void byteReader(){ File file = new File("1.txt"); //使用Try自动关闭流 try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){ //核心内容 byte[] bytes = new byte[1024]; int len = -1; StringBuilder sb = new StringBuilder(); while ((len=bis.read(bytes))!=-1){ sb.append(new String(bytes,0,len)); } //输出结果 System.out.println(sb); } catch (IOException e) { e.printStackTrace(); } }
字符缓冲流
与上面的许多过程相似(如:通过Try,流被自动关闭)
//输出字符缓冲流 public static void charWriter(){ File file = new File("1.txt"); try { Writer writer = new FileWriter(file,true); //为字符流提供缓冲,已达到高效读取的目的 BufferedWriter bw = new BufferedWriter(writer); String info = "adasd奥哈"; bw.write(info); //writer自动关闭 bw.close(); } catch (IOException e) { e.printStackTrace(); } } //输入字符缓冲流 public static void charReader(){ File file = new File("1.txt"); try { Reader reader = new FileReader(file); //为字符流提供缓冲,已达到高效读取的目的 BufferedReader br = new BufferedReader(reader); char[] chars = new char[1024]; int len = -1; while ((len=br.read(chars))!=-1){ System.out.println(new String(chars,0,len)); } //reader自动关闭 br.close(); } catch (IOException e) { e.printStackTrace(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)