下载工具类
/**
* 下载工具
*/
class DownloadUtil {
public static void downloadFromUrl(String urlStr, String saveDirPath, String saveFileName) throws IOException {
/*
获取输入流
*/
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// httpURLConnection.setConnectTimeout(1000 * 10);
// httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
InputStream inputStream = httpURLConnection.getInputStream();
/*
创建文件, 根据文件路径创建输出流.
*/
File saveDir = new File(saveDirPath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File saveFile = new File(saveDirPath + File.separator + saveFileName);
FileOutputStream outputStream = new FileOutputStream(saveFile);
/*
读取输入流, 写入输出流.
*/
byte[] buffer = new byte[1024 * 1024];
while (true) {
int length = inputStream.read(buffer);
if (length != -1) {
outputStream.write(buffer, 0, length);
} else {
break;
}
}
/*
关闭流
看顺序: 先开后关, 后开先关.
看依赖: 如果a依赖b, 那么先关a再关b.
*/
outputStream.close();
inputStream.close();
System.out.println("下载成功, 文件名: " + saveFileName);
}
}
测试类
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 创建线程的3种方式:
* 1. 继承Thread, 重写run()方法, 调用start()方法.
*/
public class DemoExtendsThread2 extends Thread {
private String urlStr;
private String saveDirPath;
private String saveFileName;
public DemoExtendsThread2(String urlStr, String saveFilePath, String saveFileName) {
this.urlStr = urlStr;
this.saveDirPath = saveFilePath;
this.saveFileName = saveFileName;
}
@Override
public void run() {
try {
DownloadUtil.downloadFromUrl(urlStr, saveDirPath, saveFileName);
} catch (IOException e) {
e.printStackTrace();
System.out.println("下载资源时异常, 文件名: " + saveFileName);
}
}
public static void main(String[] args) {
DemoExtendsThread2 thread1 = new DemoExtendsThread2(
"https://www.runoob.com/wp-content/uploads/2013/12/iostream2xx.png",
"C:\\Users\\jsmws\\Desktop",
"1.png");
DemoExtendsThread2 thread2 = new DemoExtendsThread2(
"https://csdnimg.cn/medal/xiguanyangchengLv1.png",
"C:\\Users\\jsmws\\Desktop",
"2.png");
DemoExtendsThread2 thread3 = new DemoExtendsThread2(
"https://csdnimg.cn/medal/up2_1024@240.png",
"C:\\Users\\jsmws\\Desktop",
"3.png");
thread1.start();
thread2.start();
thread3.start();
}
}