Java之多线程下载网络资源
2013-08-14 17:54
399 查看
package com.download; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; public class Downloader { public void download() throws IOException { String fileName = "YNote.exe"; String path = "http://download.ydstatic.com/notewebsite/downloads/YNote.exe"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); int fileLength = conn.getContentLength(); RandomAccessFile file = new RandomAccessFile(fileName,"rw"); file.setLength(fileLength); file.close(); conn.disconnect(); int threadNum = 10; //线程数 //每条线程下载的长度 int threadLength = fileLength % threadNum == 0 ? fileLength/threadNum : fileLength/threadNum + 1; for(int i=0;i<threadNum;i++) { int startPosition = i * threadLength; //开始写入文件的位置 RandomAccessFile threadFile = new RandomAccessFile(fileName,"rw"); threadFile.seek(startPosition); new DownloadThread(i, path, startPosition, threadFile, threadLength).start(); } } class DownloadThread extends Thread { private int id; private int startPosition; private RandomAccessFile file; private int threadLength; private String path; public DownloadThread(int i,String p,int s,RandomAccessFile f,int l) { id = i; path = p; startPosition = s; file = f; threadLength = l; } @Override public void run() { super.run(); try{ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes="+startPosition+"-"); InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024*10]; int len = -1; int length = 0; while(length<threadLength && (len=is.read(buffer))!=-1) { file.write(buffer,0,len); length += len; System.out.println("Thread"+(id+1)+" 已经下载"+length+"/"+threadLength); } file.close(); is.close(); System.out.println("Thread"+(id+1)+" 已经下载完成"); }catch(Exception e){ e.printStackTrace(); System.out.println("Thread"+(id+1)+" 下载失败"); } } } }
本文出自 “白马坡居士” 博客,请务必保留此出处http://lauwai.blog.51cto.com/7444153/1272991
相关文章推荐
- Java多线程下载网络资源
- java多线程下载网络资源(支持断点续传)
- Java 网络编程——多线程下载图片
- 多线程使用-java网络开发-文件下载
- java 下载网络资源的源码供参考
- java网络编程:RandomAccessFile, URLConnection和多线程机制实现了Http下载
- HttpUrlConnection实现多线程下载网络资源
- java网络编程和io,多线程结合完成文件上传和下载案例
- Java Nio 多线程网络下载
- JAVA多线程下载网络文件
- JAVA多线程下载网络文件
- java网络编程之Http多线程下载应用实例
- java学习_小程序(四线程断点网络资源下载,即时进度反馈)
- java实现多线程下载网络文件
- 【图片下载-代码】java下载网络图片资源例子
- Java Nio 多线程网络下载
- 关于java Io流的操作,复制(多个文件)、删除、剪切、下载网络资源
- 网络编程--JAVA之多线程下载后续:断点续存
- JAVA多线程下载网络文件