缓冲流
BufferedReader 字符输入缓冲流
BufferedWriter 字符输出缓冲流
实际上都是 Reader 和Writer 的包装流,所以在他们的构造方法中,传入的是Reader 和Writer 的对象。
构造方法摘要 |
|
BufferedReader |
|
BufferedReader |
|
构造方法摘要 |
|
BufferedWriter(Writer out) |
|
BufferedWriter(Writer out, int sz) |
例如:创建BufferedReader 和 BufferedWriter 对象的时候。
Reader in = new FileReader(“hello.txt”);
BufferedReader bufferedReader = new BufferedReader(in);
Reader out = new FileReader(“hello4.txt”);
BufferedWriter bufferedWriter = new BufferedWriter (out);
最方便的是:
BufferedReader 中有读取一行的方法
readLine()
读取一个文本行
关闭IO流的时候, 也比较方便:直接关闭包装流,内部会关闭节点流:
bufferedReader .close();
bufferedWriter .close();
练习:
利用BufferedInputStream 和BufferedOutputStream 完成 hello.txt 文件到 hello5.txt 文件的复制
/**
* 利用BufferedInputStream和 BufferedOutputStream 完成 hello.txt 文件到 hello5.txt
* 文件的复制.
*
* @throws IOException
*
*/
@Test
publicvoid testBufferedInputStreamAndBufferedOutputStream()
throwsIOException {
InputStreamin = new FileInputStream("hello.txt");
BufferedInputStreambufferedInputStream = new BufferedInputStream(in);
OutputStreamout = new FileOutputStream("hello5.txt");
BufferedOutputStreambufferedOutputStream = new BufferedOutputStream(out);
byte[]buffer = new byte[1024];
intlen = 0;
while((len = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer,0, len);
}
bufferedInputStream.close();
bufferedOutputStream.close();
}
小结:
1.BufferedInputStream缓冲流和BufferedOutputStream 缓冲流是对 inputStream
和OutputStream 的包装,在创建对象的时候,是传入inputStream和OutputStream 的对象,然后用这个BufferedInputStream和BufferedOutputStream 来读写的能够有更高的效率、
2.在关闭流的时候,只需要关闭缓冲流,而不用手动关闭底层的节点流