文件处理工具类

文件处理工具类

AppFileUtils
package com.example.hatech_env.server.easyExcel.utils;

import cn.com.hatechframework.utils.response.ResponseCode;
import com.example.hatech_env.config.constants.ExcelConstant;
import com.example.hatech_env.config.exception.BusinessException;
import com.example.hatech_env.server.common.enums.FileTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class AppFileUtils {
    private AppFileUtils() {
    }

    /**
     * 得到文件上传的路径
     * 目录:src\main\resources\template\
     */
    public static String PATH = "";

    static {
        try {
            File file = new File("");
            PATH = file.getCanonicalPath() + "\\src\\main\\resources\\template";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取windows/linux的项目根目录
     *
     * @return 项目根目录
     */
//    public static String getConTextPath() {
//        String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//        if ("usr".equals(fileUrl.substring(1, 4))) {
//            fileUrl = (fileUrl.substring(0, fileUrl.length() - 16));//linux
//        } else {
//            fileUrl = (fileUrl.substring(1, fileUrl.length() - 16));//windows
//        }
//        return fileUrl;
//    }


    /**
     * 获取文件file.properties的路径设置为主目录
     */
//    static {
//        InputStream stream = AppFileUtils.class.getClassLoader().getResourceAsStream("file.properties");
//        Properties properties = new Properties();
//        try {
//            properties.load(stream);
//            PATH = properties.getProperty("path");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 文件下载
     *
     * @param response 响应
     * @param path     文件存放的绝对路径
     * @param oldName  下载文件名
     * @return org.springframework.http.ResponseEntity
     */
    public static ResponseEntity<Object> downloadFile(HttpServletResponse response, String path, String oldName) {

        //4.使用绝对路径+相对路径去找到文件对象
        File file = new File(path);

        //5.判断文件是否存在
        if (file.exists()) {
            try {
                try {
                    //如果名字有中文 要处理编码
                    oldName = URLEncoder.encode(oldName, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //把file转成一个bytes
                byte[] bytes = FileUtils.readFileToByteArray(file);
                HttpHeaders header = new HttpHeaders();
                //封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
                header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                //设置下载的文件的名称
                header.setContentDispositionFormData("attachment", oldName);
                //创建ResponseEntity对象
                ResponseEntity<Object> entity = new ResponseEntity<Object>(bytes, header, HttpStatus.CREATED);
                return entity;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        } else {
            PrintWriter out;
            try {
                out = response.getWriter();
                out.write("no file");
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    /**
     * 根据相对路径删除硬盘上文件
     *
     * @param path 相对路径
     */
    public static void deleteFileUsePath(String path) {
        String realPath = PATH + path;
        //根据文件
        File file = new File(realPath);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 根据相对路径更改文件名
     * mv /easyExcel/temp7.xlsx  /easyExcel/rename.xlsx
     *
     * @param filePath    相对路径 /easyExcel/temp7.xlsx
     * @param newFileName 新文件名 rename.xlsx
     * @return 文件的绝对路径
     */
    public static String updateFileName(String filePath, String newFileName) {
        Map<String, String> fileDirAndFileName = getFileDirAndFileName(filePath);
        //获取存放文件的目录
        String dirPath = fileDirAndFileName.get("dir");
        //获取删除路径
        String relativeFilePath = fileDirAndFileName.get("fileName");
        //copy文件为新名称文件
        copyFile(filePath, dirPath, newFileName);
        //删除源文件
        removeFileByPath(relativeFilePath);
        return dirPath + File.separator + newFileName;
    }

    /**
     * 根据相对路径删除图片
     * rm /easyExcel/newFile2.xlsx
     *
     * @param filePath 文件的相对路径 /easyExcel/newFile2.xlsx
     */
    public static void removeFileByPath(String filePath) {
        //找到文件
        try {
            File file = new File(PATH, filePath);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件的复制  cp  /usr/local/test.txt /usr/bin/newFile.txt
     *
     * @param filePath    目标文件相对地址  /usr/local/test.txt
     * @param newPath     新文件相对地址 /usr/bin
     * @param newFileName 新文件名 newFile.txt
     */
    public static void copyFile(String filePath, String newPath, String newFileName) {
        //非空判断
        if (StringUtils.isEmpty(filePath) && StringUtils.isEmpty(newPath) && StringUtils.isEmpty(newFileName)) {
            return;
        }
        try (FileOutputStream fos = new FileOutputStream(newPath + File.separator + newFileName);
             FileInputStream fis = new FileInputStream(new File(filePath))) {
            final byte[] bytes = new byte[1024];
            while (fis.read(bytes) != -1) {
                fos.write(bytes);
            }
            fos.flush();
        } catch (IOException e) {
            log.error("文件复制出现问题!");
            log.error(e.getMessage());
        }
    }


    /**
     * @param filePath 文件的相对路径 /a/b/c/d.txt
     * @return map集合  dir : 文件存放目录路径  fileName:文件名
     */
    public static Map<String, String> getFileDirAndFileName(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }
        //获取存放文件的目录 /a/b/c
        String dirPath = filePath.substring(0, filePath.lastIndexOf(File.separator));
        //获取删除路径 d.txt
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
        Map<String, String> map = new HashedMap<>();
        map.put("pre", dirPath);
        map.put("fileName", fileName);
        return map;
    }


    /**
     * 读取目录下的所有文件路径
     *
     * @param dir       目录
     * @param fileNames 保存文件名的集合
     * @return void     所有的文件路径保存到参数fileNames中
     */
    public static void findFileList(File dir, List<String> fileNames) {
        // 判断是否存在目录
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        // 读取目录下的所有目录文件信息
        String[] files = dir.list();
        assert files != null;
        // 循环,添加文件名或回调自身
        for (String s : files) {
            File file = new File(dir, s);
            // 如果文件
            if (file.isFile()) {
                // 添加文件全路径名
                fileNames.add(dir + "\\" + file.getName());
                log.info("fileNames:" + fileNames.toString());
            } else {
                // 如果是目录、回调自身继续查询
                findFileList(file, fileNames);
            }
        }
    }


    /**
     * 检查文件类型
     *
     * @param file         文件
     * @param fileTypeEnum 文件类型枚举类
     */
    public static void checkFileType(MultipartFile file, FileTypeEnum fileTypeEnum) {
        if (file == null) {
            throw new BusinessException(ResponseCode.NOT_FOUND.code(), "请上传文件");
        }
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            throw new BusinessException(ResponseCode.NOT_FOUND.code(), "请上传文件");
        }
        if (!fileName.toUpperCase().endsWith(fileTypeEnum.getValue())) {
            throw new BusinessException(ResponseCode.NOT_FOUND.code(), "请上传." + fileTypeEnum.getValue() + "文件");
        }
    }

    /**
     * 压缩所有的excel
     */
    public static void excelZip() {
        //压缩文件名
        String fileName = ExcelConstant.ZIP_NAME;
        //excel存放路径
        File file_excel = new File(ExcelConstant.EXCEL_PATH);
        //压缩包路径
        File file_rar = new File(ExcelConstant.RAR_PATH);
        //存放excels下面的所有文件名
        List<String> fileNames = new ArrayList<>();
        //查询excels下面的所有文件名
        findFileList(file_excel, fileNames);
        //zip压缩路径不存在就创建
        if (!file_rar.exists()) {
            file_rar.mkdirs();
        }
        try (
                //创建输出流
                FileOutputStream fos = new FileOutputStream(ExcelConstant.RAR_PATH + fileName);
                //创建输出压缩流
                ZipOutputStream zos = new ZipOutputStream(fos)
        ) {

            for (String name : fileNames) {
                //创建输入流
                try (
                        FileInputStream fis = new FileInputStream(name)
                ) {
                    //创建新条目
                    String[] zipNames = ExcelConstant.EXCEL_PATH.split("[\\\\]");
                    //使用"E:\\hatech_env\\excels\\";中的excels进行分隔。然后取掉前面的\
                    ZipEntry zipEntry = new ZipEntry(name.split(zipNames[zipNames.length - 1])[1].substring(1));
                    //放入容器
                    zos.putNextEntry(zipEntry);
                    //开始写入
                    byte[] buffer = new byte[1024];
                    while (fis.read(buffer) != -1) {
                        zos.write(buffer);
                    }
                    //第一个文件压缩成功后,它会自动关闭输入流
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值