您的位置:首页 > 理论基础 > 计算机网络

多线程从网络下载文件

2015-08-10 20:11 435 查看
主类:

public class DownThreadDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
int threadNum = 3;
long fileLen = 0;
long numPerThread = 0;
long left = 0;
URL url = null;
URLConnection connection = null;
String fileName = "e:\\temp\\downlo.jpg";
RandomAccessFile[] raf = new RandomAccessFile[threadNum];
InputStream[] is = new InputStream[threadNum];
try {
url = new URL(
"http://img.bizhi.sogou.com/images/2014/08/22/830201.jpg");
// 打开网路连接
connection = url.openConnection();
// 计算文件大小
fileLen = connection.getContentLengthLong();
// 每个线程处理的文件大小
numPerThread = fileLen / threadNum;
// 最后一块
left = fileLen % threadNum;
// openConnection().getInputStream()
is[0] = url.openStream();
raf[0] = new RandomAccessFile(fileName, "rw");
raf[0].setLength(fileLen);
// 分别为每个线程创建一个从网络读取的流与写入文件的流。
for (int i = 0; i < threadNum; i++) {
if (i != 0) {
is[i] = url.openStream();
raf[i] = new RandomAccessFile(fileName, "rw");
}
if (i == threadNum - 1) {
new MultyDown(i * numPerThread, (i + 1) * numPerThread
+ left, is[i], raf[i]).start();
} else {
new MultyDown(i * numPerThread, (i + 1) * numPerThread,
is[i], raf[i]).start();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("end------");
}

}


线程类:

public class MultyDown extends Thread {
private long start, end;
private InputStream is;
private RandomAccessFile raf;

public MultyDown() {
// TODO Auto-generated constructor stub
}

public MultyDown(long start, long end, InputStream is, RandomAccessFile raf) {
// TODO Auto-generated constructor stub
this.start = start;
this.end = end;
this.is = is;
this.raf = raf;
}

@Override
public void run() {
// TODO Auto-generated method stub

int len = 0;
int size = 0;
byte[] b = new byte[24];
try {
// 跳到文件指定位置
is.skip(start);
raf.seek(start);
while ((len = is.read(b)) != -1 && size < (end - start)) {
raf.write(b, 0, len);
size += len;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: