文件处理工具

package com.thtf.zwdsj.fangjia.utils;

import com.thtf.zwdsj.code.common.exception.CommonException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @BelongsProject: xiaozhire0goods
 * @BelongsPackage: com.lzq.demoUse
 * @Author: 小智RE0 --- 学习记录
 * @Date: 2022/12/8 21:36
 * @Description: TODO
 */
public class FileMutilUnZip {


    //处理解压zip
    public static List<Path> dealUnZip(String zipPath, String targetZipPath) {
        List<Path> sourcesList = new ArrayList<>();
        if (zipPath.endsWith(".zip")) {
            dealzip(zipPath, targetZipPath);
        }
        try (Stream<Path> paths = Files.walk(Paths.get(targetZipPath))) {
            List<Path> result = paths
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
//            result.forEach(System.out::println);
            for (int i = 0; i < result.size(); i++) {
                String filePath = result.get(i).toString();
                if (filePath.endsWith(".zip")) {
//                    System.out.println(filePath);
                    dealzip(filePath, result.get(i).getParent().toString() + "/");
                    File deleteFile = new File(filePath);
                    deleteFile.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (Stream<Path> paths = Files.walk(Paths.get(targetZipPath))) {
            List<Path> result = paths
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
//            result.forEach(System.out::println);
//            for (int i = 0; i <result.size() ; i++) {
//                String filePath = result.get(i).toString();
//                if (filePath.endsWith(".xlsx") || filePath.endsWith(".xls")) {
//                    String fileName1 = result.get(i).getFileName().toString();
//                    String fileName = System.currentTimeMillis() + "_" + result.get(i).getFileName();
//                    System.out.println(fileName1);
//                    System.out.println(fileName);
//                }
//            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sourcesList;
    }

    //处理文件解压;
    public static void dealzip(String zipSourcePath, String targetZipPath) {
        //判断目标地址是否存在,如果没有就创建
        File pathFile = new File(targetZipPath);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(zipSourcePath, Charset.forName("gbk"));
            //若zip中含有中文名文件,换GBK
            //zip = new ZipFile(zipPath, Charset.forName("GBK"));
            //遍历里面的文件及文件夹
            Enumeration entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zipFile.getInputStream(entry);
                //也就是把这个文件加入到目标文件夹路径;
                String outpath = (targetZipPath + zipEntryName).replace("/", File.separator);
                //String outpath = targetZipPath.replace("/", File.separator);
                //不存在则创建文件路径
                File file = new File(outpath.substring(0, outpath.lastIndexOf(File.separator)));
                if (!file.exists()) {
                    file.mkdirs();
                }
                File outPathFile = new File(outpath);
                //文件夹就不解压;
                if (outPathFile.isDirectory()) {
                    continue;
                }
                OutputStream out = new FileOutputStream(outpath);
                byte[] bf = new byte[2048];
                int len;
                while ((len = in.read(bf)) > 0) {
                    out.write(bf, 0, len);
                }
                in.close();
                out.close();
            }
            zipFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 将MultipartFile转换为File
     *
     * @param outFilePath 参数
     * @param multiFile   参数
     * @return 执行结果
     */
    public static File multipartFileToFile(String outFilePath, MultipartFile multiFile) {
        // 获取文件名
        if (null == multiFile) {
            return null;
        }
        String fileName = multiFile.getOriginalFilename();
        if (null == fileName) {
            return null;
        }
        try {
            File toFile;
            InputStream ins;
            ins = multiFile.getInputStream();
            //指定存储路径
            toFile = new File(outFilePath.concat(File.separator).concat(multiFile.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            return toFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static MultipartFile getMultipartFileByInputStream(InputStream input, String fileName) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , fileName);
        try (
                OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
        return new CommonsMultipartFile(item);
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

    public static List<File> getAllFile(File dirFile) {
        // 如果文件夹不存在或着不是文件夹,则返回 null
        if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile())
            return null;

        File[] childrenFiles = dirFile.listFiles();
        if (Objects.isNull(childrenFiles) || childrenFiles.length == 0)
            return null;

        List<File> files = new ArrayList<>();
        for (File childFile : childrenFiles) {
            // 如果是文件,直接添加到结果集合
            if (childFile.isFile()) {
                files.add(childFile);
            }
            //以下几行代码取消注释后可以将所有子文件夹里的文件也获取到列表里
//            else {
//                // 如果是文件夹,则将其内部文件添加进结果集合
//                List<File> cFiles = getAllFile(childFile);
//                if (Objects.isNull(cFiles) || cFiles.isEmpty()) continue;
//                files.addAll(cFiles);
//            }
        }
        return files;
    }

    public static MultipartFile[] getMultipartFileList(String path) {
        File file = new File(path);
        List<File> allFile = getAllFile(file);
        List<MultipartFile> multipartFileList = new ArrayList<>();
        for (File file1 : allFile) {
            multipartFileList.add(getMultipartFile(file1));
        }
        return multipartFileList.toArray(new MultipartFile[multipartFileList.size()]);
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead;
            int bytes = 8192;
            byte[] buffer = new byte[bytes];
            while ((bytesRead = ins.read(buffer, 0, bytes)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> parsePath(Path path) {
        Map result = new HashMap<String, String>();
        String[] str = path.toString().split("/");
        if (str.length == 1) {
            str = path.toString().split("\\\\");
        }
        List<String> collect = Arrays.stream(str).filter(s -> s.contains("_")).collect(Collectors.toList());
        if (collect.size() == 0) throw new CommonException("无法解析路径");
        for (String s : collect) {
            String[] split = s.split("_");
            boolean splitHead = Pattern.matches("^[0-9]*$", split[0]);
            boolean splitTail = Pattern.matches("^[0-9]*$", split[1]);
            if (splitHead && splitTail) {
                result.put("reportPeriod", split[0]);
                result.put("zonePosition", split[1]);
                return result;
            }
        }
        return result;
    }


}
package com.thtf.zwdsj.fangjia.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @创建人 qinyangyang
 * @创建时间 2022/11/7
 * @描述
 */
public class FileUtil {

    /**
     * 功能:压缩多个文件,输出压缩后的zip文件流
     *
     * @param sourcePath:源文件路径
     * @param zipFileName:压缩后的文件名
     * @param response:           Http响应
     */
    public static void zipFiles(String sourcePath, String zipFileName, HttpServletResponse response) throws IOException {
        File[] files = new File(sourcePath).listFiles();
        byte[] buf = new byte[1024];
        // 获取输出流
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            response.reset(); // 重点突出
            // 不同类型的文件对应不同的MIME类型
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + zipFileName + ".zip");

            // ZipOutputStream类:完成文件或文件夹的压缩
            out = new ZipOutputStream(bos);
            for (int i = 0; i < files.length; i++) {
                in = new FileInputStream(files[i]);
                // 给列表中的文件单独命名
                out.putNextEntry(new ZipEntry(files[i].getName()));
                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            System.out.println("压缩完成.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        }
    }

    /**
     * 功能:压缩多个文件,输出压缩后的zip 返回路径
     * @param sourcePath
     * @param zipFileName
     * @return
     * @throws IOException
     */
    public static String zipFile(String sourcePath, String zipFileName) throws IOException {
        String outPath = sourcePath + "/" + zipFileName + ".zip";
        File[] files = new File(sourcePath).listFiles();
        byte[] buf = new byte[1024];
        // 获取输出流
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(outPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            // ZipOutputStream类:完成文件或文件夹的压缩
            out = new ZipOutputStream(bos);
            for (int i = 0; i < files.length; i++) {
                in = new FileInputStream(files[i]);
                // 给列表中的文件单独命名
                out.putNextEntry(new ZipEntry(files[i].getName()));
                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            System.out.println("压缩完成.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        }
        return outPath;
    }

    public static void deleteFile(File file) {
        File[] files = file.listFiles();
        if (files != null) {//如果包含文件进行删除操作
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    //删除子文件
                    files[i].delete();
                } else if (files[i].isDirectory()) {
                    //通过递归的方法找到子目录的文件
                    deleteFile(files[i]);
                }
                files[i].delete();//删除子目录
            }
        }
    }

    public static void isExist(String outPath) {
        File outFile = new File(outPath);
        if (!outFile.exists()) {
            try {
                outFile.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

老式xls

package com.thtf.zwdsj.fangjia.utils;

import com.thtf.zwdsj.fangjia.utils.excelUtils.ExcelImport;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;

import java.io.File;
import java.lang.reflect.Field;
import java.util.*;

public class JxlUtils {

    /**
     * @param encoding 出现中文 需要 gbk 无 utf8
     * @throws Exception
     */
    public static List<Map<String, Object>> exportXls(File file, String encoding) throws Exception {
        List<Map<String, Object>> data = new ArrayList();
        List header = new ArrayList();
        WorkbookSettings workbookSettings = new WorkbookSettings();
        workbookSettings.setEncoding(encoding);//防止乱码情况
        // 1. 打开 Excel 文件
        Workbook workbook = Workbook.getWorkbook(file, workbookSettings);
        // 2. 获取第一个工作表 Sheet
        Sheet sheet = workbook.getSheet(0);
        // 3. 遍历所有行和列,并打印单元格内容
        for (int row = 0; row < sheet.getRows(); row++) {
            Map rowData = new HashMap();
            for (int col = 0; col < sheet.getColumns(); col++) {
                if (row == 0) {
                    header.add(sheet.getCell(col, row).getContents());
                } else {
                    rowData.put(header.get(col), sheet.getCell(col, row).getContents());
                }
            }
            if (row > 0) {
                data.add(rowData);
            }
        }
        // 4. 关闭 Excel 文件
        workbook.close();
        return data;
    }

    /**
     * ExcelImport 对象
     *
     * @param t
     * @param dataMap
     * @return
     */
    public static Map<String, Object> getValue(Class t, Map<String, Object> dataMap) {
        Map<String, Object> data = new HashMap<>();
        Field[] fields = t.getDeclaredFields();
        Arrays.stream(fields).forEach(item -> {
            ExcelImport annotation = item.getAnnotation(ExcelImport.class);
            if (annotation != null) {
                String value = annotation.value();
                if (value.contains(",")) {
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (dataMap.get(s) == null) continue;
                        data.put(item.getName(), dataMap.get(s));
                    }
                } else {
                    data.put(item.getName(), dataMap.get(value));
                }
            }
        });
        return data;
    }

    public static List<Map<String, Object>> conversion(File file, String encoding, Class t) throws Exception {
        List data = new ArrayList();
        List<Map<String, Object>> mapList = exportXls(file, encoding);
        for (Map<String, Object> map : mapList) {
            data.add(getValue(t, map));
        }
        return data;
    }

}

 

posted @ 2023-10-08 17:11  chen1777  阅读(19)  评论(0)    收藏  举报