关于BufferedOutputStream高效的问题
java新人一枚,在学习java 字节输出流时有些困惑。以FileOutputStream为例,复制一个MP3(10M)文件代码如下
FileInputStream fis = new FileInputStream("E:\\test.mp3"); //输入流
FileOutputStream fos = new FileOutputStream("e:\\test2.mp3"); //输出流
int len = 0; //读取字节数
byte buf[] = new byte[1024]; //缓冲区
while((len = fis.read(buf)) != -1)
{
fos.write(buf,0,len); //将缓冲区的数据写入硬盘。
}
这个时间是312ms;
而使用BufferedOutputStream包装下的话
FileInputStream fis = new FileInputStream("E:\\test.mp3"); //输入流
FileOutputStream fos = new FileOutputStream("e:\\test2.mp3"); //输出流
BufferedOutputStream bufos = new BufferedOutputStream(fos);
int len = 0; //读取字节数
byte buf[] = new byte[1024]; //缓冲区
while((len = fis.read(buf)) != -1)
{
bufos .write(buf,0,len); //将缓冲区的数据写入硬盘。
}
这个时间是140ms。
查看过源码 调用的也是write方法,第一种方法已近使用了缓冲区了,为什么第二种会比第一种方法快?很是不解。