創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!

今天就跟大家聊聊有關(guān)Java中如何實現(xiàn)下載多線程文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
Java實現(xiàn)多線程文件下載思路:
1、基本思路是將文件分段切割、分段傳輸、分段保存。
2、分段切割用到HttpUrlConnection對象的setRequestProperty("Range", "bytes=" + start + "-" + end)方法。
3、分段傳輸用到HttpUrlConnection對象的getInputStream()方法。
4、分段保存用到RandomAccessFile的seek(int start)方法。
5、創(chuàng)建指定長度的線程池,循環(huán)創(chuàng)建線程,執(zhí)行下載操作。
首先,我們要先寫一個方法,方法的參數(shù)包含URL地址,保存的文件地址,切割后的文件開始位置和結(jié)束位置,這樣我們就能把分段文件下載到本地。并且這個方法要是run方法,這樣我們啟動線程時就直接執(zhí)行該方法。
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;
}
}
當(dāng)前題目:Java中如何實現(xiàn)下載多線程文件-創(chuàng)新互聯(lián)
標(biāo)題網(wǎng)址:http://chinadenli.net/article14/ccgode.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、搜索引擎優(yōu)化、微信小程序、用戶體驗、網(wǎng)站改版、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容