問題引出
眾所周知,Buffered In/OutputStream 因為有緩沖區(qū),所以減少了與硬盤的交互次數(shù),提高了效率,但是在測試復制文件的速度時,欠著的速度卻遠慢于后者
代碼:
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\\視頻項目\\作業(yè)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\\視頻項目\\作業(yè)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();
}
}
多次實驗后發(fā)現(xiàn)copy1的運行時間在30 s左右,但copy2僅需70 ms(MP4的大小14.7M)
原因
Buffered In/OutputStream雖然內(nèi)部有緩沖區(qū),但是在外部仍然需要定義一個byte數(shù)組
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\\視頻項目\\作業(yè)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\\視頻項目\\作業(yè)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();
}
}
現(xiàn)在復制時copy1的速度為20 msms左右,copy2在70 ms左右,帶緩沖區(qū)效率確實高