叨叨兩句
- 愈來愈難啦!乾死它們!
題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");
}
}