主要用到的类

  • 地址类: URL
  • http类: HttpURLConnection
  • 输入流: InputStream
  • 输出流: FileOutputStream

上代码

package com.demo01;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

public class TestURL {
    public static void main(String[] args) throws Exception {
    	// 下载地址
        String downURL = "https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2771978851,2906984932&fm=26&gp=0.jpg";
        // 地址
        URL url = new URL(downURL);
        // 获取文件后缀名
        String fileName = "";
        int index = url.getFile().lastIndexOf(".");
        if (index != -1) {
            fileName = url.getFile().substring(index);
        }

        // 打开地址
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        // 获取流
        InputStream is = urlConnection.getInputStream();

        // 写入流
        Random random = new Random();
        FileOutputStream fos = new FileOutputStream("UrlDown" + random.nextInt(1000) + fileName);

        // 写入文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer,0,len);
        }

        // 关闭流
        fos.close();
        is.close();
        urlConnection.disconnect(); // 断开连接
    }
}

Logo

「智能机器人开发者大赛」官方平台,致力于为开发者和参赛选手提供赛事技术指导、行业标准解读及团队实战案例解析;聚焦智能机器人开发全栈技术闭环,助力开发者攻克技术瓶颈,促进软硬件集成、场景应用及商业化落地的深度研讨。 加入智能机器人开发者社区iRobot Developer,与全球极客并肩突破技术边界,定义机器人开发的未来范式!

更多推荐