FileUtils

该文件工具类提供了多种文件操作方法,包括删除文件、上传资源、拷贝文件、获取文件MD5、获取文件扩展名等。上传资源方法会保存MultipartFile到指定路径,并返回文件的长度、MD5、原始文件名、新文件名、路径和扩展名。下载文件方法则通过HttpServletResponse响应文件供下载。此外,还包含获取指定文件夹下所有文件路径和计算资源路径的功能。
摘要由CSDN通过智能技术生成
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件工具类
 */
public class FileUtils{
    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 删除文件
     * @param file true成功false失败
     */
    public static boolean deleteFile(File file) {
        boolean flag = false;
        try {
            if (file.isFile()) {
                flag = file.delete();
            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 删除文件
     * @param fileName 为空直接返回false,不做其他处理 true成功false失败
     */
    public static boolean deleteFile(String fileName) {
        if(StringUtils.isBlank(fileName)){
            return false;
        }else{
            return deleteFile(new File(fileName));
        }
    }

    /**
     * 上传资源
     * @param file MultipartFile文件
     * @param path 相对路径
     * @param sourceFileName 原文件名称
     */
    public static Map<String,String> MultipartFileUpload(MultipartFile file, String path, String sourceFileName){
        Map<String,String> map = new HashMap<>();
        InputStream is = null;
        FileOutputStream fos = null;
        File newFile = null;
        try{
            File tpath = new File(DynamicUtils.RESOURCE_BASE_PATH + path);
            //创建文件夹
            if (!tpath.exists()) {
                tpath.mkdirs();
            }
            String fileName = UUIDUtils.create32UUID() + "." + getSuffix(sourceFileName);
            newFile = new File(DynamicUtils.RESOURCE_BASE_PATH + path + fileName);
            is = file.getInputStream();
            fos = new FileOutputStream(newFile);
            byte[] bu = new byte[1024];
            int len;
            while ((len = is.read(bu)) > 0) {
                fos.write(bu, 0, len);
            }
            fos.close();
            is.close();
            //获取资源信息
            map.put("length", PubUtils.toStr(newFile.length()));
            map.put("md5", getMd5(newFile));
            map.put("oldFileName", sourceFileName);
            map.put("fileName", fileName);
            map.put("path", path + fileName);
            map.put("suffix", getSuffix(fileName));
        } catch (Exception e) {
            logger.info("上传文件失败", e);
        } finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.gc();
        }
        return map;
    }

    /**
     * 拷贝文件
     * @param srcFileStr
     * @param descFileStr
     */
    public static void copyFile(String srcFileStr, String descFileStr){
        try {
            File srcFile = new File(srcFileStr);
            File descFile = new File(descFileStr);
            org.apache.commons.io.FileUtils.copyFile(srcFile, descFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件MD5
     * @param file
     */
    public static String getMd5(File file){
        String rtn = "";
        try {
            rtn = DigestUtils.md5Hex(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rtn;
    }

    /**
     * 获取路径扩展名
     * @param path
     */
    public static String getSuffix(String path){
        if(StringUtils.isNotBlank(path) && StringUtils.contains(path, ".")){
            return path.substring(path.lastIndexOf(".") + 1, path.length());
        }else{
            return "";
        }
    }

    /**
     * 计算基本资源路径
     * @param app 应用代码
     * @param business 业务代码
     * @param sourceType 资源类型
     */
    public static String getFilePath(String app, String business, String sourceType){
        return ConstantUtils.RESOURCE_PATH_TPL
                .replace("{app}", "")
                .replace("{business}", PubUtils.toStr(business, "dft"))
                .replace("{resource-type}", sourceType)
                .replace("{date}", "")
                .replace("//", "/");
    }

    /**
     * 获取指定文件夹下所有文件路径
     *
     * @param path java.util.List<java.io.File>
     */
    public static List<File> getFiles(String path) throws Exception {
        //目标集合fileList
        List<File> fileList = new ArrayList<>();
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileIndex : files) {
                //如果这个文件是目录,则进行递归搜索
                if (fileIndex.isDirectory()) {
                    getFiles(fileIndex.getPath());
                } else {
                    //如果文件是普通文件,则将文件句柄放入集合中
                    fileList.add(fileIndex);
                }
            }
        }
        return fileList;
    }

    /**
     * 下载项目根目录下doc下的文件
     * @param response response
     * @param filePath 文件名 返回结果 成功或者文件不存在
     */
    public static void downloadFile(HttpServletResponse response, String filePath) {
        File file = new File(filePath);
        if(!file.exists()){
            return ;
        }
        String fileName = file.getName();
        File path = null;
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            response.setHeader("Content-Length", String.valueOf(bis.available()));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
            return;
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大道至简@EveryDay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值