創新互聯www.cdcxhl.cn八線動態BGP香港云服務器提供商,新人活動買多久送多久,劃算不套路!
今天就跟大家聊聊有關Java中如何實現下載多線程文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
Java實現多線程文件下載思路:
1、基本思路是將文件分段切割、分段傳輸、分段保存。
2、分段切割用到HttpUrlConnection對象的setRequestProperty("Range", "bytes=" + start + "-" + end)方法。
3、分段傳輸用到HttpUrlConnection對象的getInputStream()方法。
4、分段保存用到RandomAccessFile的seek(int start)方法。
5、創建指定長度的線程池,循環創建線程,執行下載操作。
首先,我們要先寫一個方法,方法的參數包含URL地址,保存的文件地址,切割后的文件開始位置和結束位置,這樣我們就能把分段文件下載到本地。并且這個方法要是run方法,這樣我們啟動線程時就直接執行該方法。
public class DownloadWithRange implements Runnable { private String urlLocation; private String filePath; private long start; private long end; DownloadWithRange(String urlLocation, String filePath, long start, long end) { this.urlLocation = urlLocation; this.filePath = filePath; this.start = start; this.end = end; } @Override public void run() { try { HttpURLConnection conn = getHttp(); conn.setRequestProperty("Range", "bytes=" + start + "-" + end); File file = new File(filePath); RandomAccessFile out = null; if (file != null) { out = new RandomAccessFile(file, "rwd"); } out.seek(start); InputStream in = conn.getInputStream(); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) != -1) { out.write(b, 0, len); } in.close(); out.close(); } catch (Exception e) { e.getMessage(); } } public HttpURLConnection getHttp() throws IOException { URL url = null; if (urlLocation != null) { url = new URL(urlLocation); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); return conn; } }