将网络资源文件转存本地

package com.qiniu.ufop.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;



在线文件转byte

    public static byte[] downloadImage(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        try (InputStream in = url.openStream();
             ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            int bytesRead;
            byte[] data = new byte[1024];
            while ((bytesRead = in.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            return buffer.toByteArray();
        }
    }

/**
 * @Description
 * @project
 * @author:hf
 * @date:
 */
@Slf4j
public class CommonUtil {

    private static final String path="D:/usr/local/outDir/";

    private static final String suffix=".mp4";

    private static final int size=1024;

    /**
     * @Description: 根据url保存文件到本地
     * @Author: hf
     * @Time: 2021/4/1 11:38
     */
    public  static String downloadFromUrl(String url){
        //String fileName="D:\\"+getUUID(url)+".mp4";
        long startTime=System.currentTimeMillis();
        log.info("startTime:"+startTime);
        String fileName=getUUID(url);
        InputStream is =null;
        FileOutputStream outstream =null;
        try {
            URL urlVideo = new URL(url);
            URLConnection con = urlVideo.openConnection();
            //超时响应时间为10秒
            con.setConnectTimeout(10 * 1000);
            is = con.getInputStream();
            byte[] bs = new byte[size];
            File videofile = new File(fileName);
            if (!videofile.getParentFile().exists()) {
                try {
                    videofile.getParentFile().mkdirs();
                    videofile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            outstream = new FileOutputStream(videofile);
            //写入数据
            int len;
            while((len=is.read(bs)) != -1){
                outstream.write(bs, 0, len);
            }
           log.info("耗时:"+(System.currentTimeMillis()-startTime)+"ms");
        }catch (Exception e){
            log.error(e.getMessage());
        }finally {
            try {
                outstream.close();
                is.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return fileName;
    }

   /**
    * @Description: 本地文件转byte
    * @Author: hf
    * @Time: 2021/4/1 14:35
    */
    public static byte[] file2Byte(String filePath) {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        byte[] data =null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream(size);
            byte[] b = new byte[size];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
             data = bos.toByteArray();
        } catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            try {
                fis.close();
                bos.close();
            } catch (IOException e) {
                log.error("getBytesByFile:"+e.getMessage());
            }
        }
        return data;
    }

    /**
     * @Description: url文件转byte
     * @Author: hf
     * @Time: 2021/4/1 14:23
     */
    public static byte[] video2byte(String path){
        byte[] data = null;
        URL url = null;
        InputStream input = null;
        ByteArrayOutputStream output =null;
        try{
            url = new URL(path);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();
            output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
        }catch (Exception e) {
            log.error("video2byte:"+e.getMessage());
        }finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                log.error("video2byte:"+e.getMessage());
            }
        }
        return data;
    }
    /**
     * @Description: 根据url获取文件路径
     * @Author: hf
     * @Time: 2021/4/1 14:23
     */
    public static synchronized String getUUID(String url){
        UUID uuid=UUID.nameUUIDFromBytes(url.getBytes());
        String str = uuid.toString();
        String uuidStr=str.replace("-", "");
        //直接拼接视频文件地址
        uuidStr=path+uuidStr+suffix;
        return uuidStr;
    }


    public static void main(String[] args) throws Exception {
        String url="https://media.w3.org/2010/05/sintel/trailer.mp4";
        System.out.println(downloadFromUrl( url));
        //System.out.println( file2Byte(downloadFromUrl( url)));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值