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

通过Url下载网络资源

程序员文章站 2022-05-05 20:42:47
...

步骤

  1. 通过下载地址创建url对象
  2. 连接到这个资源的http
  3. 从获取输入流
  4. 读取并写入
  5. 关闭连接

具体代码

package Url;

import java.io.File;
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 {

        //1.通过下载地址创建url对象
        URL url = new URL("https://i1.hdslb.com/bfs/face/[email protected]_140h_1c.webp");
        //2.连接到这个资源的http
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        //3.从获取输入流
        InputStream inputStream = urlConnection.getInputStream();
        //4.读取并写入
        byte[] buffer = new byte[1024];
        int len;
        FileOutputStream fileOutputStream = new FileOutputStream(new File("3.jpg"));
        while((len=inputStream.read(buffer)) != -1){
            fileOutputStream.write(buffer,0,len);
        }
        //5.关闭连接
        fileOutputStream.close();
        inputStream.close();
        urlConnection.connect();
    }
}