Java網路程式設計之單執行緒下載檔案設定顯示進度(一)
阿新 • • 發佈:2019-01-24
下載檔案的時候,如果為了使用者友好,都會給予進度條提醒使用者,那麼怎麼做呢?
其實很簡單,首先獲取伺服器檔案的大小
urlConnection.getContentLength(),然後在讀取檔案過程計算檔案百分比增長即可
/** * 檔案下載工具 by sam on 2015/11/5. */ public final class FileUtil { /** * 單執行緒下載檔案 * @param url 檔案的網路地址 * @param path 儲存的檔案地址 */ public static void dowanload(String url, String path) throwsIOException { System.out.println("下載中..."); InputStream inputStream = null; RandomAccessFile randomAccessFile = null; try { HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(10 * 1000); File file = new File(path); if (!file.getParentFile().exists()) file.getParentFile().mkdir(); if (file.exists()) file.delete(); file.createNewFile(); intresponseCode = urlConnection.getResponseCode(); if (responseCode >= 200 && responseCode < 300) { inputStream = urlConnection.getInputStream(); int len = 0; byte[] data = new byte[4096]; int progres = 0; //用於儲存當前進度(具體進度) int maxProgres = urlConnection.getContentLength();//獲取檔案 randomAccessFile = new RandomAccessFile(file, "rwd"); randomAccessFile.setLength(maxProgres);//設定檔案大小 int unit = maxProgres / 100;//將檔案大小分成100分,每一分的大小為unit int unitProgress = 0; //用於儲存當前進度(1~100%) while (-1 != (len = inputStream.read(data))) { randomAccessFile.write(data, 0, len); progres += len;//儲存當前具體進度 int temp = progres / unit; //計算當前百分比進度 if (temp >= 1 && temp > unitProgress) {//如果下載過程出現百分比變化 unitProgress = temp;//儲存當前百分比 System.out.println("正在下載中..." + unitProgress + "%"); } } inputStream.close(); System.out.println("下載完成..."); } else { System.out.println("伺服器異常..."); } } finally { if (null != inputStream) { inputStream.close(); } if (null != randomAccessFile) { randomAccessFile.close(); } } } public static void main(String[] args) throws IOException { String path = "D:\\abc\\abc.jpg"; String url = "http://www.dowei.com/d/file/mingxing/bagua/20151105/9e88df8cd5dd243b31eff7a4f7d53f89.jpg"; FileUtil.dowanload(url, path); } }