准备工作
首先需要commons io的工具包,下载连接附上
Commons IO – Download Apache Commons IO
新建一个lib包,将下载解压之后将commons-io-2.11.0.jar复制到idea的lib包中
add as library将其添加到库中,添加之后是可展开的
实现
先写一个下载器,用java.io的File类实现
//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String name) throws IOException {
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
}catch (IOException e){
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
public class TestThread2 extends Thread{
//图片地址
private String url;
//文件名
private String name;
public TestThread2(String url,String name){
this.url = url;
this.name = name;
}
@SneakyThrows
@Override
public void run(){
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&fmt=auto&app=138&f=JPEG?w=632&h=500","1.jpg");
TestThread2 t2 = new TestThread2("https://img2.baidu.com/it/u=957523443,3301463541&fm=253&fmt=auto&app=138&f=JPEG?w=700&h=497","2.jpg");
TestThread2 t3 = new TestThread2("https://img1.baidu.com/it/u=2306413288,4195946486&fm=253&fmt=auto&app=120&f=JPEG?w=680&h=655","3.jpg");
t1.start();
t2.start();
t3.start();
}
}