最近要做一个回放视频下载的功能,顺便研究了一下下载工具类,做个笔记以后也能用
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");
}
}