在idea中复制如下代码,即可下载网络上的任意资源到自己电脑,例如一些收费歌曲,视频等:
package com.itheima.reggie.Thread; (包名按照自己的修改)
import java.io.FileOutputStream; (导入必要的工具类)
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//下载网络资源 (网络上的一切资源本质都是 流stream)
public class UrlDown {
public static void main(String[] args) throws IOException {
// 1.下载地址(地址随着自己的爱好去改变)
URL url = new URL("https://m701.music.126.net/20230203234634/88ae333213ba0226982da73d0393b0a7/jdyyaac/5453/5652/0052/c9ae0506bea82f7c1eaf786c123e9bba.m4a");
// 2.连接到这个资源
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("123e9bba.m4a");
byte[] bytes = new byte[1024];
int len;
while((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len); //写出这个数据
}
fileOutputStream.close();
inputStream.close();
urlConnection.disconnect();//断开连接
}
}
![](https://img-blog.csdnimg.cn/img_convert/fb41f86244c4e08a0d2521d9f2bf4fb9.jpeg)
很快几秒钟下载成功,m4a文件就是 音乐文件格式
![](https://img-blog.csdnimg.cn/img_convert/1f17905be36ca4ddc9850515ffe4c60b.jpeg)
打开,可以播放啦
![](https://img-blog.csdnimg.cn/img_convert/ad08776e2db839ba86b23ff36ec54f33.jpeg)
![](https://img-blog.csdnimg.cn/img_convert/13c145c3f29aeb89675bf82a613605f4.jpeg)