java根据地址下载文件示例

在获取到文件地址的情况下,下载文件到本地制定目录。

package org.jeecg.utils;

import java.io.*;
import java.net.*;

public class DownloadFile {
    public static void main(String[] args) throws Exception {
        // 文件地址
        String fileUrl = "https://pixabay.com/get/g085642ee3a41c8090cd9307ce03d0c6f56c0bed3e0c21bac13ccdc4d5469a320b5135950a447ab0660a788c9a294540172aa677f689ec8d529e1a2861841d57ccb87e0ed09aa23b1303796f00c6719b4_1920.jpg?attachment=";
        // 目标文件保存地址
        String savePath = "D:/Downloads/pixabay-photo-1366919.jpeg";
        
        URL url = new URL(fileUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.76");//防止报403
        // 获取文件长度
        int fileLength = httpURLConnection.getContentLength();
        // 创建输入流启动下载
        InputStream inputStream = httpURLConnection.getInputStream();
        byte[] buffer = new byte[1024];
        int readCount = 0;
        // 创建输出流,将文件保存到本地
        FileOutputStream fileOutputStream = new FileOutputStream(savePath);
        while ((readCount = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, readCount);
        }
        // 关闭输入输出流
        fileOutputStream.close();
        inputStream.close();
        System.out.println("下载完成!");
    }
}

你可能感兴趣的:(java,开发语言,下载)