为了体会Buffered的流在进行传输文件中的加速体现,特意做了下面的例子进行了验证,主要对比的是一个复制的操作,因为比较小的文件体现不出来的速度的快慢,所以,特意下载了一个mp3格式的文件来进行测试,具体的代码如下:
首先是不带buffered的流的传输:
//对比效率---->与上面形成对比
@Test
public void TestInput() {
//指定源文件
File oldFile = new File("Barbie - Good Time.mp3");
//指定新文件
File newFile = new File("Good Time.mp3");
//指定读入写出流
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(oldFile);
os = new FileOutputStream(newFile);
//进行复制操作
int len;
byte b[] = new byte[1024];
long start = System.currentTimeMillis();
while((len = is.read(b)) != -1) {
//写操作
os.write(b, 0, len);
}
long end = System.currentTimeMillis();
System.out.println("不加入缓冲流需要花费的时间为:" + (end - start));//130
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//关流
if(os != null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
可以看到进行这个复制操作需要的时间为:159ms
而加入Buffered的流的代码如下:
@Test
public void testBufferedInputStream() {
//主要用来测试加入缓冲流的作用,加快传输的速度---->主要用来测试buffered的速度提升
File file = new File("Barbie - Good Time.mp3");
//文件格式为mp3需要用字节流来进行处理
BufferedInputStream bis = null;
//写操作
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(new FileOutputStream("Good Time.mp3"));
int len;
byte[] b = new byte[1024];
long start = System.currentTimeMillis();
while((len = bis.read(b)) != -1) {
//写
bos.write(b, 0, len);
}
long end = System.currentTimeMillis();
System.out.println("加入缓冲流后需要花费的时间为:" + (end-start));//52
}catch (IOException e) {
e.printStackTrace();
}
//关流
if(bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
具体运行的时间如下: