Java IO流--字符缓冲流
同样的字符缓冲流也有对应的两个类
BufferedReader:从字符输入流读取字符,缓冲字符,实现高效读取。
BufferedWriter:将字符写入字符输出流,缓冲字符,实现高效写入。
字符输入流(FileReader)本身自带缓存,但是加入字符缓冲流,可以使字符读写效率更高。
BufferedReader和 BufferedWriter默认缓存大小是8K,同时可以指定此缓存大小。
代码示例:
package com.seven.javaSE; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; public class CharBufferStream { public static void main(String[] args) { read(); write(); } public static void read() { try { Reader read = new FileReader("c:/TestFile/source.txt",Charset.forName("utf-8")); BufferedReader br = new BufferedReader(read); char [] cc = new char[10]; int len=-1; while((len=br.read(cc))!=-1) { System.out.println(new String(cc,0,len)); } br.close(); System.out.println("文件读取结束"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void write() { try { Writer write = new FileWriter("c:/TestFile/target.txt"); BufferedWriter bw = new BufferedWriter(write); bw.write("字符缓冲流"); bw.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("写入文件成功"); } }
本文来自博客园,作者:藤原豆腐渣渣,转载请注明原文链接:https://www.cnblogs.com/javafufeng/p/16386183.html