java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestThread2 extends Thread {
private List<String> urlList;
public TestThread2() {
}
public TestThread2(List<String> urlList) {
this.urlList = urlList;
}
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
urlList.forEach(x -> {
try {
System.out.println(Thread.currentThread().getName() + "执行");
webDownLoader.downloader(x);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
public static void main(String[] args) {
List<String> list = Arrays.asList("https://pic.xxxxx-cdn.com//1/130702.jpg",
"https://pic.xxxxx-cdn.com//1/106152.jpg",
"https://pic.xxxxx-cdn.com//1/100603.jpg",
"https://pic.xxxxx-cdn.com//1/98446.jpg",
"https://pic.xxxxx-cdn.com//1/98436.jpg",
"https://pic.xxxxx-cdn.com//1/98411.jpg",
"https://pic.xxxxx-cdn.com//1/98176.jpg",
"https://pic.xxxxx-cdn.com//1/98072.jpg");
//切分数组
List<List<String>> lists = splitList(list, 3);
lists.forEach(x -> {
TestThread2 td = new TestThread2(x);
td.start();
});
}
/**
* @param list 数组
* @param partNum 切分次数
* @return 先按平均值切分,最后一次全部
*/
private static List<List<String>> splitList(List<String> list, int partNum) {
List<List<String>> rList = new ArrayList<>();
int avgNum = list.size() / partNum;
System.out.println(avgNum + ":平均数");
for (int part = 0; part < partNum; part++) {
//判断start起始位置 0 : avgNum * part
int start = 0 == part ? 0 : avgNum * part;
//判断最后一次结束位置 list.size() : start + avgNum
int end = partNum == part + 1 ? list.size() : start + avgNum;
System.out.println(String.format("第%s次,起始:%s 位置:%s", part + 1, start, end));
List<String> subList = new ArrayList<>();
for (int i = start; i < end; i++) {
// System.out.println(list.get(i));
subList.add(list.get(i));
}
rList.add(subList);
}
System.out.println(rList);
return rList;
}
}
class WebDownLoader {
public void downloader(String url) throws IOException {
class WebDownLoader {
public void downloader(String url) throws IOException {
// 提取文件名
String fileName = url.substring(url.lastIndexOf('/') + 1); // "filename.txt"
// 提取名称部分(例如去掉扩展名)
String name = fileName.substring(0, fileName.lastIndexOf('.')); // "filename"
FileUtils.copyURLToFile(new URL(url), new File(fileName));
}
}
FileUtils.copyURLToFile(new URL(url), new File(fileName));
}
}
