学习一下网络知识和看看大佬的博客,直接贴代码,odk
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
@SuppressWarnings("all")
public class myTest {
public static void main(String[] args) throws Exception {
DownLoadImg("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png",
"img.png","C:\\Users\\HP\\Desktop");
}
public static void DownLoadImg(String urlString,String fileName,String savePath) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection connection = url.openConnection();
// 设置超时时间
connection.setConnectTimeout(8000);
// 使用字节流1MB
byte[] data = new byte[1024*1024];
// 每次下载的最大数据长度
int len = 0;
// 缓冲输入流
BufferedInputStream bi = new BufferedInputStream(connection.getInputStream());
// 你想要保存的文件夹
File file = new File(savePath);
// 如果不存在就创建
if(!file.exists()){
file.mkdirs();
}
// 缓冲输出流
BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(file.getPath()+"\\"+fileName));
// 循环读取获取的数据,并进行输出流写出到本地磁盘
while((len = bi.read(data))!=-1){
bo.write(data,0,len);
}
System.out.println("下载完成");
// 关闭输入输出流连接
bo.close();
bi.close();
}
}