缓冲流的作用:增加读写数据效率
对比基本的字节输入流,字节输出流增加一个缓冲区(数组)提高基本流的读写速度
例子:文件的复制
package io.test;
import java.io.*;
/**
*使用普通的基本流进行一个个字节的Copy 毫秒:13269
* 使用普通的缓冲流进行一个个字节的Copy 毫秒:60
* 使用普通的基本流通过byte[1024]的Copy 毫秒:20
*使用普通的缓冲流通过byte[1024]的Copy 毫秒:10
*/
public class CopyDemo {
public static void main(String[] args) throws IOException {
//mother1();
//mother2();
//mother3();
mother4();
}
/**
* 使用普通的缓冲流通过byte[1024]的Copy
*/
private static void mother4() throws IOException {
long startTime=System.currentTimeMillis();
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\study\\1.jpg"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\study\\5.jpg"));
int len=0;
byte[] bytes=new byte[1024];
while ((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
// bos.flush();
}
bos.close();
bis.close();
long endTime=System.currentTimeMillis();
System.out.println("毫秒:"+(endTime-startTime));
}
/**
* 使用普通的基本流通过byte[1024]的Copy
*/
private static void mother3() throws IOException {
long startTime=System.currentTimeMillis();
FileInputStream fis=new FileInputStream("D:\\study\\1.jpg");
FileOutputStream fos=new FileOutputStream("D:\\study\\4.jpg");
int len=0;
byte[] bytes=new byte[100];
while((len=fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fos.close();
fis.close();
long endTime=System.currentTimeMillis();
System.out.println("毫秒:"+(endTime-startTime));
}
/**
* 使用普通的缓冲流进行一个个字节的Copy
*/
private static void mother2() throws IOException {
long startTime=System.currentTimeMillis();
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\study\\1.jpg"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\study\\3.jpg"));
int len=0;
while ((len=bis.read())!=-1){
bos.write(len);
}
bos.close();;
bis.close();
long endTime=System.currentTimeMillis();
System.out.println("毫秒:"+(endTime-startTime));
}
/**
* 使用普通的基本流进行一个个字节的Copy
*/
private static void mother1() throws IOException {
long startTime=System.currentTimeMillis();
FileInputStream fis=new FileInputStream("D:\\study\\1.jpg");
FileOutputStream fos=new FileOutputStream("D:\\study\\2.jpg");
int len=0;
while((len=fis.read())!=-1){
fos.write(len);
}
fos.close();
fis.close();
long endTime=System.currentTimeMillis();
System.out.println("毫秒:"+(endTime-startTime));
}
}
字符缓冲流(BufferedReader):
特有方法:
String readLine() 读一行文字。不会读取换行符号
字符缓冲流(BufferedWrider)
特有方法
void newLine() 写一行行分隔符。