//第一种
public static void main(String[] args) throws Exception {
// 1.下载地址
URL url = new URL("需要下载的文件地址例如:https://tse2-mm.cn.bing.net/th/id/OIP.V0bcfKTWPk1eGZyLBkcJmwHaEo?w=253&h=180&c=7&o=5&dpr=1.19&pid=1.7");
// 2.连接到这个资源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("存放的地址例如:test.png");
byte[] bytes = new byte[1024];
int len;
while ((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len); //写出数据
}
fileOutputStream.close();
inputStream.close();
urlConnection.disconnect(); // 断开连接
}
//第二种 使用jdk提供的类
public static void main(String[] args) throws IOException {
FileUtils.copyURLToFile(new URL("需要下载的文件地址例如:https://tse2-mm.cn.bing.net/th/id/OIP.V0bcfKTWPk1eGZyLBkcJmwHaEo?w=253&h=180&c=7&o=5&dpr=1.19&pid=1.7"),new File("存放的地址例如:test.png));
}