在玩爬蟲的過程中,其中有一部分是下載視頻,利用原生的HttpURLConnection獲得獲得inputStream之後,將輸入流寫入到本地文件中,形成mp4格式的視頻文件,發現最初使用的方法特別慢,想找尋更好的方法,提升效率。
1.原始方法
//pathName就是文件保存的路徑
BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(pathName);
System.out.println("文件大約:"+(conn.getContentLength()/1024)+"K");
byte[] by = new byte[1024];
int len = 0;
while((len=bi.read(by))!=-1){
fos.write(by,0,len);
}
fos.close();
bi.close();
這裏在自己的機器上面進行網絡請求進行的測試,一個5M左右的文件得3秒鐘左右。
@Test
public void copyFile() throws FileNotFoundException, IOException{
/* long startTime = System.currentTimeMillis();
File file = new File("D:\\testDouyin.mp4");
File otherFile = new File("D:\\dy.mp4");
FileUtils.copyInputStreamToFile(new FileInputStream(file), otherFile);
long endTime = System.currentTimeMillis();
log.info("消耗時間:" + (endTime - startTime));*/
/*
File file = new File("D:\\testDouyin.mp4");
long startTime = System.currentTimeMillis();
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(file));
FileOutputStream fos = new FileOutputStream("D:\\dy.mp4");
byte[] by = new byte[2048];
int len = 0;
while((len=bi.read(by))!=-1){
fos.write(by,0,len);
}
fos.close();
bi.close();
long endTime = System.currentTimeMillis();
log.info("消耗時間:" + (endTime - startTime));
*/
/*
long startTime = System.currentTimeMillis();
File file = new File("D:\\testDouyin.mp4");
File otherFile = new File("D:\\dy.mp4");
Files.copy(new FileInputStream(file), otherFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
long endTime = System.currentTimeMillis();
log.info("消耗時間:" + (endTime - startTime));
*/
long startTime = System.currentTimeMillis();
File file = new File("D:\\photocreator.jar");
File otherFile = new File("D:\\ph.jar");
FileInputStream inStream = new FileInputStream(file);
FileOutputStream outStream = new FileOutputStream(otherFile);
FileChannel in = inStream.getChannel();
FileChannel out = outStream.getChannel();
in.transferTo(0, in.size(), out);
long endTime = System.currentTimeMillis();
log.info("消耗時間:" + (endTime - startTime));
}
本機本地測試直接讀取文件操作,使用commons IO的FileUtils時間爲22毫秒;使用字節數組方式,5M的文件27毫秒;將byte[]調整爲2048,操作時間爲19毫秒。NIO的操作類時間26毫秒。又進行了大文件的測試,84M的文件,還是commons IO的FileUtils的速度稍快一些,當然這裏的字節數組給的初始值較小,給更大的初始值,速度更快。
上面給出的代碼中,最後一種方法是最快的,使用FileChannel進行文件的傳輸,這裏使用的nio相關的知識。