这里我从网络上下载一首音乐为例
代码:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLDown {
public static void main(String[] args) throws Exception {
// 这里的url是文件的地址
URL url = new URL("https://m801.music.126.net/20211026163617/bceac5328a192ce0402b1732fce6377e/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/11365054437/4df4/5c80/c6bd/a72f4db2b71f7267294f6f80fdf56b15.m4a");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// 创建输入流接受文件
InputStream inputStream = urlConnection.getInputStream();
// 创建输出流写入文件
FileOutputStream fileOutputStream = new FileOutputStream("src/躺在凌晨五点半的海岸2.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();
}
}