注册了博客,感觉自己就很帅~

关于多线程网络文件下载

package com.softeem.thread;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 完成一个多线程断点下载工具
 * 1.通过提供的网络文件地址,下载该文件
 * 2.要求使用多个线程同时下载,
 * 3.实时更新下载进度(0%~100%)
 * 4.要求能够实现断点功能(扩展)
 */
public class ThreadNetFileCopy extends Thread{
	
	private String sourceURL;	// 下载源的位置URL
	private	File target;// 保存到本地的目标文件
	private long start;	// 当前线程拷贝的开始位置
	private long end;	// 当前线程拷贝的结束位置
	
	public long current = 0;


	public ThreadNetFileCopy(String sourceURL, File target, long start, long end) {
		super();
		this.sourceURL = sourceURL;
		this.target = target;
		this.start = start;
		this.end = end;
	}


	@Override
	public void run() {
		InputStream is = null;
		RandomAccessFile rsf = null;
		URL url = null;
		try {
			url = new URL(sourceURL);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setReadTimeout(10000);
			int code = conn.getResponseCode();
			System.out.println(Thread.currentThread().getName()+"开始拷贝...");
			if(code == HttpURLConnection.HTTP_OK){
				is = conn.getInputStream();
				rsf = new RandomAccessFile(target, "rw");
				is.skip(start); // 如何将源URL的文件分为四段
				rsf.seek(start);// seek到段点的位置,分段拷贝
				
				byte[] b = new byte[1024];
				int length = 0;
				while((length = is.read(b)) != -1 && current <= (end - start)){
					current += length; // 记录当前进程已下载的总字节数
					rsf.write(b, 0, length);
				}
			}
			System.out.println("完成拷贝");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rsf != null) rsf.close();
				if(is != null) is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws IOException{
		String sourceURL = "http://192.168.46.254:8888/easyBuy/images/plmm.jpg";
		String sourceName = sourceURL.substring(sourceURL.lastIndexOf("/"));
		File target = new File("D:\\", sourceName);
		URL url = new URL(sourceURL);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		// 实时更新下载进度
		
		long item = conn.getContentLengthLong()/4;
		for(int i = 0; i < 4; i++){
			new ThreadNetFileCopy(sourceURL, target, i*item, (i+1)*item).start();
		}
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值