欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

URL下载网络资源

程序员文章站 2022-05-05 20:41:41
...
package com.sean.base.netStudy;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author 关根普
 * @create 2021-03-01 16:11
 */
public class URLDown {
    public static void main(String[] args) throws Exception{
        //1下载地址
        URL url = new URL("https://m10.music.126.net/20210301164814/5a093ab7ba65a049298b2c3ca23cf999/yyaac/550e/550f/065e/bd39690760bee6aa29371462ceff933b.m4a");

        //2.连接到这个资源 HTTP
        HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
        InputStream inputStream=urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("SecurityFile.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);//写出这个数据
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接

    }
}

相关标签: url https java