文章目录
1. 概念
就是根据指定的一个url来对想要的资源进行下载,然后保存至指定的目录
2. 步骤
2.1. 传入下载地址
2.2. 根据传入的地址连接到资源
2.3. 通过流读写出数据
2.4. 关闭流资源
2.5. 关闭资源连接
3.实现
3.1 Java代码实现
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* @description:根据url下载资源测试
* @return
*/
public class URLDownload {
public static void main(String[] args) throws IOException {
//1.下载地址
URL url = new URL("http://m10.music.126.net/20201123230543/981a4b190210c2523f73a80c125db212/ymusic/5153/510c/0f59/f928038072ff09c222a083680e1f64ed.mp3");
//2. 根据地址连接到这个资源
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//3. 写出数据,通过流
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("F:\\e.mp3");
byte[] bytes = new byte[1024];
int len;
while ((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
//4. 关闭资源
fileOutputStream.close();
inputStream.close();
//5. 关闭资源连接
urlConnection.disconnect();
}
}
3.2 结果:
文件夹: