首先搞好配置文件
package com.company;
import java.io.*;
import java.net.URL;
import java.util.UUID;
import java.net.MalformedURLException;
public class DownloadPicFormURL {
public static void downloadPicture(String urlList, String path) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream()); // 文件读取
// 如果目录不存在就创建目录
File file = new File(path);
if(!file.getParentFile().exists()){
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream = new FileOutputStream(file); // 文件写出
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
fileOutputStream.write(outputStream.toByteArray());
// 连接关闭
dataInputStream.close();
fileOutputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
然后写个测试文件,进行下载测试
package com.company;
import java.util.UUID;
public class DownloadPicTest {
public static void main(String[] args) {
String url = "https://editor-ue.588ku.com/?picId=814078&sourceC=master&sourceP=qk_reg_mblb";
String path="C:\\Users\\大魔王\\Pictures\\Saved Pictures";
DownloadPicFormURL.downloadPicture(url,path + UUID.randomUUID() + ".jpg");
}
}