Java檔案操作--inputStream轉為file
阿新 • • 發佈:2018-11-19
在玩爬蟲的過程中,其中有一部分是下載視訊,利用原生的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相關的知識。