作用:提高读写效率,是高级流。
一.字节缓冲流
1.原理
底层自带了长度为8192的缓冲区提高性能
2.构造方法
方法名称 | 说明 |
public BufferedInputStream(InputStream is) | 把基本流包装成高级流,提高读取数据的性能 |
public BufferedOutputStream(OutputStream os) | 把基本流包装成高级流,提高写出数据的性能 |
//获取没执行之前的时间
long start = System.currentTimeMillis();
//拷贝文件
BufferedInputStream bis = new BufferdeInputStream(new FileInputStream("D:\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\b.txt"));
//一次读取一个字节
int b;
while((b = bis.read() != -1)){
bos.write(b);
}
bos.close();
bis.close();
long end = System.currentTimeMillis();
System.out.println(end-start);
//获取没执行之前的时间
long start = System.currentTimeMillis();
//拷贝文件
BufferedInputStream bis = new BufferdeInputStream(new FileInputStream("D:\\a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\b.txt"));
//一次读取多个字节
byte[] bytes = new byte[1024];
int len;
while((b = bis.read() != -1)){
bos.write(bytes,0,len);
}
bos.close();
bis.close();
long end = System.currentTimeMillis();
System.out.println(end-start);
二.字符缓冲流
提升效率不明显
1.原理
底层自带了长度为8192的缓冲区提高性能。
2.构造方法
方法名称 | 说明 |
public BufferedReader(Reader r) | 把基本流变成高级流 |
public BufferedWriter(Writer r) | 把基本流变成高级流 |
3.特有方法
字符缓冲输入流特有方法 | 说明 |
public String readLine() | 读取一行数据,如果没有数据可读了,就会返回null |
BufferedReader br = new BufferedReader(new FileReader(D:\\a.txt));
String line;
//循环遍历
//在读取时,一次读取一整行,遇到回车换行结束,不会把回车换行读到内存中
while((line = br.readLine()) ! = null){
System.out.println(line);
}
br.close();
字符缓冲输出流特有方法 | 说明 |
public void newLine() | 跨平台的换行 |
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\a.txt"));
bw.write("a");
//在所有平台都能自动换行
bw.newLine();
bw.close();
注:
- 使用原则:随用随创建。
- 输入流创建时会关联文件,清空内容。