Java解析文件工具类

package com.guodi.bpm.ssxf.solution.utils;

import com.guodi.bpm.ssxf.model.vo.UnzipFileVo;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * @描述 解析文件工具类
 * @作者 梁伟浩
 * @日期 2023/11/08 17:25
 */
public class UnZipUtil {

    public static int BYTE_LEN = 10240;

    /**
     * 本地文件解压
     *
     * @param file 具体文件
     * @return 解压后的文件列表
     */
    public static List<UnzipFileVo> unzip(File file) {
        String absolutePath = file.getAbsolutePath();
        if (Objects.isNull(file) || !file.exists()) {
            return Collections.emptyList();
        }
        ZipFile zip = null;
        try {
            zip = new ZipFile(file, Charset.forName("gbk"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Objects.isNull(zip)) {
            return Collections.emptyList();
        }
        Enumeration<? extends ZipEntry> entries = zip.entries();
        List<UnzipFileVo> vos = new ArrayList<>();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String path = entry.getName();
            UnzipFileVo vo = new UnzipFileVo();
            vo.setPath(path);
            // 解析文件夹
            boolean directory = entry.isDirectory();
            if (directory) {
                vo.setType(0);
                String[] split = path.split("/");
                vo.setName(split[split.length - 1]);
                vos.add(vo);
                continue;
            }
            // 解析文件
            vo.setType(1);
            vo.setName(path.substring(path.lastIndexOf("/") + 1));
            /*StringBuilder sb = new StringBuilder();
            try (InputStream in = zip.getInputStream(entry);
                 InputStreamReader inputStreamReader = new InputStreamReader(in);
                 BufferedReader reader = new BufferedReader(inputStreamReader)) {
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            vo.setContent(sb.toString());*/
           /* try {
                InputStream inputStream = zip.getInputStream(entry);
                vo.setByteArrayOutputStream(cloneInputStream(inputStream));
            } catch (IOException e) {
                e.printStackTrace();
            }*/
            vos.add(vo);
        }
        if (Objects.nonNull(zip)) {
            try {
                zip.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return vos;
    }

    public static ByteArrayOutputStream cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传文件解压
     *
     * @param multipartFile 上传文件
     * @return 解压后的文件列表
     */
    public static List<UnzipFileVo> unzip(MultipartFile multipartFile) {
        File file = getFile(multipartFile);
        if (Objects.isNull(file)) {
            return Collections.emptyList();
        }
        List<UnzipFileVo> vos = unzip(file);
        if (file.exists()) {
            boolean delete = file.delete();
            if (delete) {
                System.out.println(file.getName() + " 临时文件删除成功!");
            } else {
                System.out.println(file.getName() + " 临时文件删除失败!");
            }
        }
        return vos;
    }

    /**
     * 上传文件解压
     *
     * @param inputStream 上传文件流
     * @return 解压后的文件列表
     */
    public static List<UnzipFileVo> unzip(InputStream inputStream) {
        File file = getFile(inputStream);
        if (Objects.isNull(file)) {
            return Collections.emptyList();
        }
        List<UnzipFileVo> vos = unzip(file);
        if (file.exists()) {
//            boolean delete = file.delete();
//            if (delete) {
//                System.out.println(file.getName() + " 临时文件删除成功!");
//            } else {
//                System.out.println(file.getName() + " 临时文件删除失败!");
//            }
        }
        return vos;
    }

    /**
     * MultipartFile 转 File
     *
     * @param inputStream 上传文件流
     * @return 本地文件
     */
    public static File getFile(InputStream inputStream) {
        String fileName = System.currentTimeMillis() + "";
        File file = new File("./" + fileName);
        int len;
        try (OutputStream os = new FileOutputStream(file);
             InputStream in = inputStream) {
            byte[] buffer = new byte[BYTE_LEN];
            while ((len = in.read(buffer, 0, BYTE_LEN)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file;
    }

    /**
     * MultipartFile 转 File
     *
     * @param multipartFile 上传文件
     * @return 本地文件
     */
    public static File getFile(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        File file = new File("./" + fileName);
        int len;
        try (OutputStream os = new FileOutputStream(file);
             InputStream in = multipartFile.getInputStream()) {
            byte[] buffer = new byte[BYTE_LEN];
            while ((len = in.read(buffer, 0, BYTE_LEN)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file;
    }

    /**
     * MultipartFile 转 File
     *
     * @param inputStream 上传文件流
     * @return 本地文件
     */
    public static File getFile(InputStream inputStream, String targetFilePath) {
        String fileName = System.currentTimeMillis() + "";
        File file = new File(targetFilePath + fileName);
        int len;
        try (OutputStream os = new FileOutputStream(file);
             InputStream in = inputStream) {
            byte[] buffer = new byte[BYTE_LEN];
            while ((len = in.read(buffer, 0, BYTE_LEN)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file;
    }

    /**
     * MultipartFile 转 File
     *
     * @param multipartFile 上传文件
     * @return 本地文件
     */
    public static File getFile(MultipartFile multipartFile, String targetFilePath) {
        String fileName = System.currentTimeMillis() + "_" + multipartFile.getOriginalFilename();
        File file = new File(targetFilePath + fileName);
        int len;
        try (OutputStream os = new FileOutputStream(file);
             InputStream in = multipartFile.getInputStream()) {
            byte[] buffer = new byte[BYTE_LEN];
            while ((len = in.read(buffer, 0, BYTE_LEN)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file;
    }


    /**
     * 解压zip压缩文件到指定目录
     *
     * @param zipPath zip压缩文件绝对路径
     * @param descDir 指定的解压目录
     */
    public static void unzipFile(String zipPath, String descDir) throws IOException {
        try {
            File zipFile = new File(zipPath);
            if (!zipFile.exists()) {
                throw new IOException("要解压的压缩文件不存在");
            }
            File pathFile = new File(descDir);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            InputStream input = new FileInputStream(zipPath);
            unzipWithStream(input, descDir);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    /**
     * 解压
     *
     * @param inputStream
     * @param descDir
     */
    public static void unzipWithStream(InputStream inputStream, String descDir) {
        if (!descDir.endsWith(File.separator)) {
            descDir = descDir + File.separator;
        }
        try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, Charset.forName("GBK"))) {
            ZipEntry zipEntry;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                String zipEntryNameStr = zipEntry.getName();
                String zipEntryName = zipEntryNameStr;
                if (zipEntryNameStr.contains("/")) {
                    String str1 = zipEntryNameStr.substring(0, zipEntryNameStr.indexOf("/"));
                    zipEntryName = zipEntryNameStr.substring(str1.length() + 1);
                }
                String outPath = (descDir + zipEntryName).replace("\\\\", "/");
                File outFile = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!outFile.exists()) {
                    outFile.mkdirs();
                }
                if (new File(outPath).isDirectory()) {
                    continue;
                }
                writeFile(outPath, zipInputStream);
                zipInputStream.closeEntry();
            }
            System.out.println("======解压成功=======");
        } catch (IOException e) {
            System.out.println("压缩包处理异常,异常信息{}" + e);
        }
    }

    //将流写到文件中
    public static void writeFile(String filePath, ZipInputStream zipInputStream) {
        try (OutputStream outputStream = new FileOutputStream(filePath)) {
            byte[] bytes = new byte[4096];
            int len;
            while ((len = zipInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException ex) {
            System.out.println("解压文件时,写出到文件出错");
        }
    }

/*    //删除文件夹及其文件
    public static void deleteFile(File file){
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //打印文件名
            System.out.println("文件名:" + f.getName());
            //文件删除
            f.delete();
        }
        boolean delete = file.delete();
        System.out.println(delete);
    }*/

    /**
     * 删除指定文件夹下的全部内容
     *
     * @param file
     */
    public static void deleteFile(File file) {
        File[] files = file.listFiles();//将file子目录及子文件放进文件数组
        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();//删除子目录
            }
        }
        file.delete();
    }

    /**
     * 删除指定文件夹下的全部内容
     *
     * @param file
     */
    public static void deleteFile(File file, String mdbPath) {
        File[] files = file.listFiles();//将file子目录及子文件放进文件数组
        if (files != null) {//如果包含文件进行删除操作
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {//删除子文件
                    if (files[i].getName().contains(".mdb")) {
                        File reFile = new File(mdbPath + "/" + files[i].getName());
                        files[i].renameTo(reFile);
                        reFile.delete();
                    } else {
                        files[i].delete();
                    }
                } else if (files[i].isDirectory()) {//通过递归方法删除子目录的文件
                    deleteFile(files[i], mdbPath);
                }
                files[i].delete();//删除子目录
            }
        }
        file.delete();
    }

}

  • 压缩包有目录,解压出来才是正常的目录
    Java解析文件工具类_第1张图片

你可能感兴趣的:(java,开发语言)