缓冲流[Buffered]
缓冲流我们可以理解为对原来的使用数组方式进行数据传输的一种增强
按照类型分为:
-
字符缓冲流:BufferedReader,BufferedWriter
-
字节换出流:BufferedInputStream,BufferedOutputStream
缓冲流的基本原理,是在创建流对象的时候,会先创建一个内置的默认大小的缓冲区,数组,通过缓冲区来读写数据.减少系统IO操作的次数,减少开销,提高程序的读写的效率.
字节缓冲流
构造方法
-
public BufferedinpuStream(inputStream input):创建一个新的缓冲输入流
-
public BufferedOutputStream(OutputStream output):创建一个新的缓冲输出流
字符缓冲流
构造方法
-
public BufferedWriter(Writer out):创建一个新的字符缓冲输出流
-
public BufferedReader(Reader in):创建一个新的字符缓冲输入流.
特有的方法
-
BufferedReader:public String readLine():读取整行的文本信息.
-
BufferedWriter:public void newLine():写入一行行分割符.由系统属性定义定义换行符号.
字符缓冲输入流代码演示
// 1.创建一个字符缓冲输入流对象,构造方法中传递一个字符输入流
BufferedReader bu = new BufferedReader(new FileReader("day29_IO\avcd.txt"));
// 2.使用字符缓冲输入流对象中的read/readLine,读取文本信息
String s ;
while ((s=bu.readLine())!=null){
System.out.println(s);
}
bu.close();
字符缓冲输出流代码演示:
// 1.创建一个字符缓冲输出流对象,构造方法中传递一个字符输出流
BufferedWriter fi = new BufferedWriter(new FileWriter("day29_IO\two.txt"));
// 2.调用字符缓冲输出流对象中的write方法,把数据写入到内存缓冲区中.
fi.write("我今天吃了西红柿炒鸡蛋");
fi.newLine();
fi.write("3d软件");
fi.newLine();
fi.write("c4d");
// 3.调用字符缓冲输出流对象中flush方法,把内存缓冲区中的数据刷新到文件中.
fi.flush();
//4.释放资源
fi.close();
普通的输入输出流和使用Buffered缓冲输出出入流的区别速度区别
private static void show02(File file) throws IOException {
//获取开始的时间
long start=System.currentTimeMillis();
//1.构建一个字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
//构建一个字节缓冲输出流
BufferedOutputStream fi = new BufferedOutputStream(new FileOutputStream("day29_IO\l.gif"));
//调用read()方法读取文件到byte数组
byte[] bytes = new byte[1024];
//确定while循环结束的条件 read()==-1
int len;//记录读取到的有效字节个数
while ((len=bis.read(bytes))!=-1){
fi.write(bytes,0,len);
}
//关闭流释放资源
fi.close();
bis.close();
//记录复制后的时间
long re=System.currentTimeMillis();
//复制所需的时间//114
System.out.println("文件复制的时间为"+(re-start)+"ms");
}
//不使用缓冲流的复制
public static void show01(File file) throws IOException {
//获取开始的时间
long start=System.currentTimeMillis();
//1.构建字节输入流
FileInputStream fi = new FileInputStream(file);
//2.构建一个字节输出流对象
FileOutputStream fw = new FileOutputStream("day29_IO\3.gif");
//调用字节输入流对象中的方法read(byte[] b)读取文件
byte[] bytes = new byte[1024];
int len;
while((len=fi.read(bytes))!=-1){
//4.把读取到的字节内容写入到目的地文件中
fw.write(bytes,0,len);
}
fw.close();
fi.close();
long sr=System.currentTimeMillis();//424
System.out.println("文件复制的时间为"+(sr-start)+"ms");
}
}