Java通过URL下载文件工具类,可直接使用。定义超时时间、获取服务端提供的文件名、根据项目所在路径保存在项目同级目录

1 篇文章 0 订阅
1 篇文章 0 订阅

Java通过URL下载文件

通过url下载文件,根据项目路径,保存至项目同级目录。文件名可自定义传入,若传入为空,则使用URL的下载服务提供的文件名。使用HttpURLConnection工具下载,可自定义下载超时时间。

下载方法为静态方法,可直接DownloadUtil.downloadFileByUrl(String url, String fileName);调用使用。

注:StringUtils为Spring包中工具类,用作判断字符串是否为空

package com.zlin.tool.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author zlin
 * @date 20191216
 */
public class DownloadUtil {

    private static final Logger logger = LogManager.getLogger(DownloadUtil.class);

    /**
     * 通过url下载文件,若文件名为空,取服务端的文件名
     * 保存在项目同级目录downloads下
     * @param url 下载链接
     * @param fileName 文件名
     */
    public static void downloadFileByUrl(String url, String fileName) throws IOException {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        try {
            // 校验URL
            new URL(url);
        }catch (MalformedURLException e) {
            logger.error(e);
            return;
        }
        HttpURLConnection urlCon = null;
        DataInputStream in = null;
        try {
            urlCon = (HttpURLConnection) new URL(url).openConnection();
            // 设置超时时长
            urlCon.setConnectTimeout(20000);
            urlCon.setReadTimeout(20000);
            int code = urlCon.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                logger.info("下载响应失败,响应code {}", code);
            }
            in = new DataInputStream(urlCon.getInputStream());
            if (StringUtils.isEmpty(fileName)) {
                // 可通过Map<String, List<String>> headerMap = urlCon.getHeaderFields();来获取所有header内容
                String contentDisposition = urlCon.getHeaderField("Content-Disposition");
                int fileNameIndex = contentDisposition.indexOf("filename=");
                fileName = contentDisposition.substring(fileNameIndex + 9, contentDisposition.indexOf(";", fileNameIndex));

            }
            writeToFileByStream(in, fileName);
        } finally {
            try {
                if (urlCon != null) {
                    urlCon.disconnect();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }
    }

    /**
     * 通过DataInputStream写入数据到文件
     * 文件保存在项目同级目录的downloads下
     * @param in 数据输入流
     * @param fileName 写入文件名
     */
    private static void writeToFileByStream(DataInputStream in, String fileName) throws IOException {
        if (StringUtils.isEmpty(fileName) || in == null) {
            return;
        }
        DataOutputStream out = null;
        try {
            out = new DataOutputStream(new FileOutputStream(createFileByFileName(fileName)));
            byte[] buffer = new byte[10240];
            int count;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }

    }

    /**
     * 通过文件名创建文件,固定为项目同级目录downloads下
     * @param fileName 待创建文件的文件名
     * @return File对象
     */
    private static File createFileByFileName(String fileName){
        File file = null;
        if (!StringUtils.isEmpty(fileName)) {
            String projectPath = new File("").getAbsolutePath();
            String upDirPath = projectPath.substring(0, projectPath.lastIndexOf(File.separator));
            File downloadDir = new File(upDirPath + File.separator + "downloads");
            if (!downloadDir.exists()) {
                boolean bool = downloadDir.mkdirs();
                if (!bool) {
                    logger.error("创建文件夹失败 {}", downloadDir.getAbsolutePath());
                }
            }
            file = new File(downloadDir.getAbsolutePath() + File.separator + fileName);
        }
        return file;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值