叨叨两句
- 越来越难啦!干死它们!
题15: 多线程下载
package com.test;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadThread extends Thread{
//正在运行的线程个数
public static int threadCount = 0;
private int startIndex;
private int endIndex;
private String path;
private int id;
public DownloadThread() {
}
public DownloadThread(int startIndex, int endIndex, String path, int id) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.path = path;
this.id = id;
threadCount++;
}
public void run() {
try {
//创建URL对象
URL url = new URL(path);
//建立连接
URLConnection conn = url.openConnection();
//配置连接
conn.setRequestProperty("Range","bytes" + startIndex + "-" + endIndex);
//通过连接获取流
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(id + ".temp");
byte[] arr = new byte[8 * 1024];
int len;
while((len = is.read(arr)) != -1) {
fos.write(arr, 0, len);
}
is.close();
fos.close();
threadCount--;
System.out.println(getName() + "下载完毕");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class FileUtil {
public static void mergeFile(String srcPath,String destPath) throws Exception {
File file = new File(srcPath);
File[] subFiles = file.listFiles(new FileFilter() {
public boolean accept(File pathname) {
if(pathname.isFile() && pathname.getName().endsWith(".temp")) {
return true;
}
return false;
}
});
FileOutputStream fos = new FileOutputStream(destPath);
for (File subFile : subFiles) {
FileInputStream fis = new FileInputStream(subFile);
byte[] arr = new byte[8 * 1024];
int len;
while((len = fis.read(arr)) != -1) {
fos.write(arr, 0, len);
}
fis.close();
}
fos.close();
System.out.println("合并完毕");
}
}
class ServerUtils {
public static int getFileLength(String path) {
try {
URL url = new URL(path);
URLConnection conn = url.openConnection();
int fileLength = conn.getContentLength();
return fileLength;
} catch(Exception e) {
return -1;
}
}
}
package com.test;
public class Test05 {
public static void main(String[] args) throws Exception {
String path = "http://ox4j4dsnp.bkt.clouddn.com/17-10-1/58878601.jpg";
int length = ServerUtils.getFileLength(path);
int count = 6;
int perLength = length / count;
for(int i = 0; i < count; i++) {
int startIndex = perLength * i;
int endIndex = perLength * (i + 1) - 1;
if(i == count - 1) {
endIndex = length - 1;
System.out.println(endIndex);
}
new DownloadThread(startIndex, endIndex, path, i).start();
}
while(DownloadThread.threadCount > 0) {
Thread.sleep(20);
}
FileUtil.mergeFile("D:\\workspace\\test","D:\\workspace\\test\\copy.jpg");
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。