多线程从网络下载文件
2015-08-10 20:11
435 查看
主类:
线程类:
public class DownThreadDemo { public static void main(String[] args) { // TODO Auto-generated method stub int threadNum = 3; long fileLen = 0; long numPerThread = 0; long left = 0; URL url = null; URLConnection connection = null; String fileName = "e:\\temp\\downlo.jpg"; RandomAccessFile[] raf = new RandomAccessFile[threadNum]; InputStream[] is = new InputStream[threadNum]; try { url = new URL( "http://img.bizhi.sogou.com/images/2014/08/22/830201.jpg"); // 打开网路连接 connection = url.openConnection(); // 计算文件大小 fileLen = connection.getContentLengthLong(); // 每个线程处理的文件大小 numPerThread = fileLen / threadNum; // 最后一块 left = fileLen % threadNum; // openConnection().getInputStream() is[0] = url.openStream(); raf[0] = new RandomAccessFile(fileName, "rw"); raf[0].setLength(fileLen); // 分别为每个线程创建一个从网络读取的流与写入文件的流。 for (int i = 0; i < threadNum; i++) { if (i != 0) { is[i] = url.openStream(); raf[i] = new RandomAccessFile(fileName, "rw"); } if (i == threadNum - 1) { new MultyDown(i * numPerThread, (i + 1) * numPerThread + left, is[i], raf[i]).start(); } else { new MultyDown(i * numPerThread, (i + 1) * numPerThread, is[i], raf[i]).start(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("end------"); } }
线程类:
public class MultyDown extends Thread { private long start, end; private InputStream is; private RandomAccessFile raf; public MultyDown() { // TODO Auto-generated constructor stub } public MultyDown(long start, long end, InputStream is, RandomAccessFile raf) { // TODO Auto-generated constructor stub this.start = start; this.end = end; this.is = is; this.raf = raf; } @Override public void run() { // TODO Auto-generated method stub int len = 0; int size = 0; byte[] b = new byte[24]; try { // 跳到文件指定位置 is.skip(start); raf.seek(start); while ((len = is.read(b)) != -1 && size < (end - start)) { raf.write(b, 0, len); size += len; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (raf != null) { try { raf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
相关文章推荐
- Apache HTTP Server .htaccess文件详解
- http和https的区别
- [网络流] 二分图匹配
- java基础第十讲——数据库、单例设计模式、服务器、项目(数据库—服务器—网络)
- BaseHTTPServer构建基本服务器
- Android 网络学习之获取服务器文本文件
- 网络爬虫初步:从访问网页到数据解析
- 网络爬虫初步:从访问网页到数据解析
- JAVA基础篇八(Java,C++中的网络)
- IOS 网络编程 + 后台保持连接
- iOS网络编程实践--NSStream实现TCP Socket iPhone客户端
- TCP粘包
- 使用http_load网站压力测试
- JQuery发送Put、Delete请求 - 摘自网络
- HTTP协议
- AsyncTask下载网络文件,并显示下载进度
- TCP/IP协议三次握手与四次握手流程解析
- 机器学习之从logistic到神经网络算法
- Burpsuite截获https数据包
- java.io.IOException: Server returned HTTP response code: 500 for URL解决办法