FileUtil


package com.thtf.zwdsj.fangjia.utils;

import org.springframework.web.multipart.MultipartFile;

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.ArrayList;
import java.util.Enumeration;
import java.util.List;
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: 
 * @Date: 2022/12/8 21:36
 * @Description: TODO
 */
public class FileMutilUnZip {
    public static void main(String[] args) {
        List list = dealUnZip("E:/2011-0101.zip", "E:/1/");
        list.forEach(System.out::println);

    }

    //处理解压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;
    }


    private 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();
        }
    }


}

 

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 (bos != null) {
                bos.flush();
                bos.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    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();//删除子目录
            }
        }
    }

}

 

posted @ 2022-11-12 16:03  chen1777  阅读(56)  评论(0)    收藏  举报