文件下载工具类

package com.gsafety.dss.common.util.file;

import com.gsafety.common.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 目前存在各种文件转成不同文件流的工具
 *
 * @author: Xouer
 * @since 2019-12-18 14:31
 */
@Component
@Slf4j
public class FileUtils {

    public ByteArrayOutputStream inputStreamToByteArray(MultipartFile file) {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            byte[] buff = new byte[1024 * 1024];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            inputStream.close();
        } catch (IOException e) {
            log.info("file stream conversion error");
            throw new BusinessException("上传文件失败");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.info(e.getMessage());
                }
            }
        }
        return swapStream;
    }

    public ByteArrayOutputStream inputStreamToByteArray(File file) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        FileInputStream filei = null;
        try {

            int rc = 0;
            byte[] buff = new byte[(int) file.length()];
            filei = new FileInputStream(file);
            while ((rc = filei.read(buff, 0, 100)) > 0) {
                stream.write(buff, 0, rc);
            }
            filei.close();
        } catch (Exception e) {
            log.info("file stream conversion error");
            throw new BusinessException("上传文件失败");
        } finally {
            if (filei != null) {
                try {
                    filei.close();
                } catch (IOException e) {
                    log.info(e.getMessage());
                }
            }
        }
        return stream;
    }


    /**
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static File amrToMP3Linux(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        File source = File.createTempFile("upload" + File.separator + UUID.randomUUID(), suffixName);
        file.transferTo(source);
        String target = System.getProperty("user.dir") + "/upload" + File.separator + UUID.randomUUID() + "1.mp3";
        log.info("执行命令开始");
        String command = "ffmpeg -i " + source.toString() + " " + target;
        Runtime runtime = Runtime.getRuntime();
        try {
            Process proc = runtime.exec(command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            int exitVal = proc.waitFor();
            log.info("the exitVal is : " + exitVal);
        } catch (IOException e) {
            log.error(e.getMessage());
        } catch (InterruptedException e) {
            log.error("ffmpeg exec cmd Exception " + e.toString());
        }
        log.info("执行命令结束");
        source.delete();
        return new File(target);
    }

    /**
     * 传入url得到返回流对象
     */
    private InputStream getStream(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setDoInput(true);
            http.setDoOutput(true);
            log.info("下载文件连接状态:" + http.getResponseCode());
            InputStream inputStream = http.getInputStream();
            return inputStream;
        } catch (MalformedURLException e) {
            log.error("URL协议格式或者路径错误", e);
            throw new BusinessException("URL协议格式或者路径错误");
        } catch (IOException e) {
            log.error("下载文件输入流转换失败", e);
        }
        return null;
    }
   /**
     * 根据文件服务器路径下载文件
     * @param fileUrlPath
     * @param filePathLocal
     * @return
     */
    private String downLoadFile(String fileUrlPath, String filePathLocal) {
        if (StringUtils.isEmpty(filePathLocal)) {
            filePathLocal = System.getProperty("java.io.tmpdir");
        }
        InputStream in = getStream(fileUrlPath);
        File folder = new File(filePathLocal);
        //构建目录
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File file = new File(filePathLocal + StringUtils.substringAfterLast(fileUrlPath, "/"));
        try {
            if (file.exists()) {
                log.info("文件已经存在,删除文件");
                file.delete();

                file.createNewFile();

            }
            if (!file.exists()) {
                log.info("文件不存在,正在创建新文件");
                file.createNewFile();
            }
            //构造输出流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            //构造byte数组
            byte[] b = new byte[1024];
            int length = 0;
            while ((length = in.read(b)) != -1) {
                //将输入流写入到输出流
                fileOutputStream.write(b, 0, length);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            in.close();
        } catch (IOException e) {
            log.info("文件本地创建失败");
            throw new BusinessException("文件下载失败");
        }
        log.info("文件下载完成");
        return file.getPath();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值