问题引出
众所周知,Buffered In/OutputStream 因为有缓冲区,所以减少了与硬盘的交互次数,提高了效率,但是在测试复制文件的速度时,欠着的速度却远慢于后者
代码:
public class Test {
public static void main(String[] args) throws IOException {
long start=System.currentTimeMillis();
copy1();
long end=System.currentTimeMillis();
sop((end-start)+"毫秒");
start=System.currentTimeMillis();
copy2();
end=System.currentTimeMillis();
sop((end-start)+"毫秒");
}
public static void copy1() throws IOException{
BufferedInputStream buf = new BufferedInputStream(new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4"));
BufferedOutputStream bufo=new BufferedOutputStream(new FileOutputStream("F:\\TCPServer.mp4"));
int ch;
while((ch=buf.read())!=-1){
bufo.write(ch);
}
buf.close();
bufo.close();
}
public static void copy2() throws IOException{
FileInputStream fin=new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4");
FileOutputStream fout=new FileOutputStream("F:\\TCPServer2.mp4");
byte [] buf=new byte[1024];
int len;
while((len=fin.read(buf))!=-1){
fout.write(buf,0,len);
}
fin.close();
fout.close();
}
}
多次实验后发现copy1的运行时间在30 s左右,但copy2仅需70 ms(MP4的大小14.7M)
原因
Buffered In/OutputStream虽然内部有缓冲区,但是在外部仍然需要定义一个byte数组
public class Test {
public static void main(String[] args) throws IOException {
long start=System.currentTimeMillis();
copy1();
long end=System.currentTimeMillis();
sop((end-start)+"毫秒");
start=System.currentTimeMillis();
copy2();
end=System.currentTimeMillis();
sop((end-start)+"毫秒");
}
public static void copy1() throws IOException{
BufferedInputStream buf = new BufferedInputStream(new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4"));
BufferedOutputStream bufo=new BufferedOutputStream(new FileOutputStream("F:\\TCPServer.mp4"));
byte [] bufb=new byte [1024];
int len;
while((len=buf.read(bufb))!=-1){
bufo.write(bufb,0,len);
}
buf.close();
bufo.close();
}
public static void copy2() throws IOException{
FileInputStream fin=new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4");
FileOutputStream fout=new FileOutputStream("F:\\TCPServer2.mp4");
byte [] buf=new byte[1024];
int len;
while((len=fin.read(buf))!=-1){
fout.write(buf,0,len);
}
fin.close();
fout.close();
}
}
现在复制时copy1的速度为20 msms左右,copy2在70 ms左右,带缓冲区效率确实高