1. 程式人生 > >字節流的三種操作方法效率對比

字節流的三種操作方法效率對比

copyfile ndt 文件 流復制 share pri file input time

public class IOStream {
public static void main(String[] args) throws IOException {
//目標文件大小:43.9M
Original ();//使用自建緩沖區方式復制文件耗時148毫秒
Buff (); //使用包裝流復制文件耗時2727毫秒
Utils ();//使用工具類復制文件耗時104毫秒
}
//使用自建緩沖區方式復制文件
private static void Original() throws IOException {

File file = new File ("source.mp4");
InputStream in = new FileInputStream (file);
OutputStream out = new FileOutputStream ("/Users/Shared/a.mp4");

long startTime = System.currentTimeMillis ();

byte[] arr = new byte[8192];
int len;
while ((len = in.read (arr) )!= -1){
out.write (arr);
}

long endTime = System.currentTimeMillis ();
System.out.println (endTime-startTime);

in.close ();
out.close ();
}
//使用包裝流方式復制文件
private static void Buff() throws IOException {
File file = new File ("source.mp4");
InputStream in = new FileInputStream (file);
BufferedInputStream bfi= new BufferedInputStream (in);
OutputStream out = new FileOutputStream ("/Users/Shared/b.mp4");
BufferedOutputStream bfo = new BufferedOutputStream (out);

long startTime = System.currentTimeMillis ();

int len;
while ((len = bfi.read () )!= -1){
bfo.write (len);
}

long endTime = System.currentTimeMillis ();
System.out.println (endTime-startTime);

bfi.close ();
bfo.close ();
}

//使用工具包復制文件
private static void Utils() throws IOException {

File file1 = new File ("source.mp4");//文件大小:43.9M
File file2 = new File ("/Users/Shared/c.mp4");

long startTime = System.currentTimeMillis ();

FileUtils.copyFile (file1,file2);

long endTime = System.currentTimeMillis ();
System.out.println (endTime-startTime);
}
}

字節流的三種操作方法效率對比