多线程下载 java_java实现多线程下载

public class MultithreadingDown {

public static void main(String[] args) throws Exception {

// 链接资源

URL url = new URL("http://localhost:8080/20140808/up/a.txt");

// 获取服务器文件的大小

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setDoInput(true);

con.setRequestMethod("GET");

con.setReadTimeout(3000);

con.connect();

int code = con.getResponseCode();

if (code == 200) {

// 获取大小

int size = con.getContentLength();

File dest = new File("F:\\scratch-file\\a01\\a.txt");

// 创建一个同等大小的文件

@SuppressWarnings("resource")

RandomAccessFile raf = new RandomAccessFile(dest, "rw");

raf.setLength(size);

// 计算每个线程应该下多少个字节

int threadCount = 3;

int sizePerThread = size / threadCount

+ (size % threadCount == 0 ? 0 : 1);

System.err.println("每个线程下载多少" + sizePerThread);

// 计算每个线程从哪里下载至少到什么地方

for (int i = 0; i 

int start = i * sizePerThread;

int end = start + (sizePerThread - 1);

System.err.println(i + ":" + start + "~" + end);

new MyThread(url, dest, start, end).start();

}

}

}

static class MyThread extends Thread {

private URL url;

private File dest;

private int start;

private int end;

public MyThread(URL uu, File dd, int s, int e) {

this.url = uu;

this.dest = dd;

this.start = s;

this.end = e;

}

@Override

public void run() {

try {

HttpURLConnection con = (HttpURLConnection) url

.openConnection();

con.setReadTimeout(3000);

con.setRequestMethod("GET");

con.setRequestProperty("range", "bytes=" + start + "-" + end);

con.setDoInput(true);

con.connect();

int code = con.getResponseCode();

if (code == 206) {

InputStream in = con.getInputStream();

byte[] b = new byte[1024];

int len = 0;

RandomAccessFile rand = new RandomAccessFile(dest, "rw");

rand.seek(start);

while ((len = in.read(b)) != -1) {

rand.write(b, 0, len);

}

rand.close();

}

System.err.println(this.getName()+"over");

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值