注意
-
为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组
-
根据数据操作单位可以把缓冲流分为:
BufferedInputStream
和BufferedQutputStream
BufferedReader
和BufferedWriter
-
缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法
-
对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush()将会使内存中的数据立刻写出
缓冲字符输入流BufferedReader
输出文件的内容
public static void testBufferedReader(){
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\workspace\\qiuzhiketang\\src\\FileTest\\tt1.txt"));
char[] chars = new char[10];
int len =0;
while ((len = bufferedReader.read(chars))!=-1){
System.out.println(new String(chars,0,len));
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
缓冲字符输出流BufferedWriter
将字符串“123abc”写入文件中
public static void testBufferedWriter(){
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\workspace\\qiuzhiketang\\src\\FileTest\\tt.txt"));
bufferedWriter.write("123abc");
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
缓冲字符流:复制文件
将一个文件的内容复制到另一个文件中
public static void copyFile(){
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\workspace\\qiuzhiketang\\src\\FileTest\\tt.txt"));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\workspace\\qiuzhiketang\\src\\FileTest\\tt1.txt"));
char[] chars = new char[10];
int len =0;
while ((len = bufferedReader.read(chars))!=-1){
bufferedWriter.write(chars);
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}