多线程下载

package com.downloadthreads;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Date;
/*
 * 多线程下载示例
 *
 * */
public class DownloadMain {
	private long startpoint;
	
	private int threadNum=5;
	
	private long filesize;
	
	private long currentPartSize;
	
	private File file=null;
	
	private File file1=null;
	
	
/*
 *打开目标资源;创建目的文件,启用线程 
 */
	public void download() throws Exception{
	
    file1=new File("D:/test//test1.txt");
    
    RandomAccessFile file=new RandomAccessFile("D:/test//test.txt","rw");
    RandomAccessFile raf=new RandomAccessFile(file1,"rw");
    //设置接收文件的大小
    raf.setLength(file.length());
    raf.close();
    filesize=file.length();
    currentPartSize=filesize/threadNum+1;
    //
	for(int i=0;i<threadNum;i++){
		startpoint=i*currentPartSize;
		 RandomAccessFile rafs=new RandomAccessFile(file1,"rw");
		 rafs.seek(startpoint);
		Thread t=new DownloadThread(startpoint,currentPartSize,rafs,file);
		t.start();
		System.out.println(t.getName());
	}
}
	public static void main(String[] args) throws Exception {
		DownloadMain main=new DownloadMain();
		System.out.println(new Date());
		main.download();
		System.out.println(new Date());
	}
}
package com.downloadthreads;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

public class DownloadThread extends Thread{
	
private long startpoint;

private long currentpartsize;

private RandomAccessFile rafs;

private RandomAccessFile file;

public DownloadThread(long startpoint, long currentpartsize,
		RandomAccessFile rafs, RandomAccessFile file) {
	super();
	this.startpoint = startpoint;
	this.currentpartsize = currentpartsize;
	this.rafs = rafs;
	this.file = file;
}
@Override
public void run() {
	int hasread;
	int lenth=0;
    byte[] b=new byte[1024];
    try {
    	file.skipBytes((int)startpoint);
		while(lenth<currentpartsize&&(hasread=file.read(b))>0){
			rafs.write(b);
			lenth+=hasread;
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	

}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值