读书人

java实现多线程上载

发布时间: 2012-11-01 11:11:32 作者: rapoo

java实现多线程下载

package my;import java.io.BufferedInputStream;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class MultiThreadDownload {/** * @param args */public static void main(String[] args) {String path = "http://blog.liuhongwei.cn/wp-content/uploads/2009/08/java-duke-guitar.png";try {new MultiThreadDownload().downLoad(path, 5);} catch (IOException e) {e.printStackTrace();}}public void downLoad(String path,int threadSize) throws IOException{URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(6000);//get the length of fileint fileLength = conn.getContentLength();//get the name of fileString fileName = path.substring(path.lastIndexOf("/"));File saveFile = new File(fileName);RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");accessFile.setLength(fileLength);accessFile.close();int block = (fileLength%threadSize ==0? fileLength/threadSize :(fileLength/threadSize+1));System.out.println(block);for(int threadID=0 ; threadID < threadSize ; threadID++){new DownThread(url, saveFile, threadID, block).start();}}private final class DownThread extends Thread{private URL url;private File saveFile;private int threadID;private int block;public DownThread(URL url, File saveFile, int threadID, int block) {this.url = url;this.saveFile = saveFile;this.threadID = threadID;this.block = block;}@Overridepublic void run() {try {//System.out.println("threadID = "+threadID+" 已启动!");int startPosition = threadID * block;int endPosition = (threadID +1)* block-1;RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");accessFile.seek(startPosition);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(6000);conn.setRequestProperty("Range", "bytes="+startPosition+"-"+endPosition);BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());bis.mark(startPosition);System.out.println("threadID = "+threadID+" 已启动!"+startPosition);byte[] buffer = new byte[1024];int len = 0;while((len=bis.read(buffer))!=-1){accessFile.write(buffer, 0, len);}bis.close();accessFile.close();//输出信息:System.out.println("threadID = "+threadID+" 已下载完成!");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

读书人网 >编程

热点推荐