下载工具类http

最近要做一个回放视频下载的功能,顺便研究了一下下载工具类,做个笔记以后也能用

package com.cnlive.gxb.sync.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpFileUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpFileUtils.class);

    /**
     * @param urlPath     下载路径
     * @param downloadDir 下载存放路径(包含文件名)
     * @return 返回下载文件
     */

    public static Boolean downloadFile(String urlPath, String downloadDir) {
        logger.info("文件下载开始.............下载路径=" + urlPath + ",存放路径=" + downloadDir);
        File file = null;
        try {

            // 统一资源
            URL url = new URL(urlPath.replaceAll(" ", "%20"));
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            //文件总长度
//            BigDecimal fileLength = new BigDecimal(Integer.toString(httpURLConnection.getContentLength()));
            long fileLength = httpURLConnection.getContentLength();
            String path = downloadDir;
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(file);
            int size = 0;
            long len = 0L;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 打印下载百分比
                System.out.println("下载了----------->" + (len * 100) / fileLength + "%");

//                System.out.println("下载了--------------》"+new BigDecimal(Integer.toString(len*100)).divide(fileLength,0,BigDecimal.ROUND_HALF_UP));
//                System.out.println("下载了--------------》"+len);
            }
            bin.close();
            out.close();
        } catch (Exception e) {
            logger.error("文件下载失败..........", e);
            return false;
        }
        return true;
    }

    @Test
    public void adc() {
        downloadFile("http://scio.vods2.cnlive.com/38/vod/2019/1025/38_f818991810dc4a63b983c811b4017ee3/ff8080816dd3d861016e02e5498c7637_1500.mp4", "d:abc/eds/2019/2.mp4");

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值