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;
}
}
public class DownloadFileWithThreadPool
{
public void getFileWithThreadPool(String urlLocation,String filePath, int poolLength) throws IOException
{
Executor threadPool = Executors.newFixedThreadPool(poolLength);
long len = getContentLength(urlLocation);
for(int i=0;i<poolLength;i++)
{
long start=i*len/poolLength;
long end = (i+1)*len/poolLength-1;
if(i==poolLength-1)
{
end =len;
}
DownloadWithRange download=new DownloadWithRange(urlLocation, filePath, start, end);
threadPool.execute(download);
}
}
public static long getContentLength(String urlLocation) throws IOException
{
URL url = null;
if (urlLocation != null)
{
url = new URL(urlLocation);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
long len = conn.getContentLength();
return len;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有