美文网首页
java对带文件夹的文件实现zip压缩解压缩记录

java对带文件夹的文件实现zip压缩解压缩记录

作者: haiyong6 | 来源:发表于2023-10-01 15:09 被阅读0次

之前记录过一篇java打包zip压缩包案例

这里补一下针对带文件夹的文件压缩和解压缩的方法。

新建ZipTest类:

package com.ly.mp.project.test;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import com.alibaba.fastjson.JSONObject;
import com.ly.mp.project.utils.IOCloseUtil;

public class ZipTest {
    /**
     * 解压到指定目录
     */
    public static List<String> unZipFiles(String zipPath,String descDir)throws IOException
    {
        return unZipFiles(new File(zipPath), descDir);
    }
    /**
     * 解压文件到指定目录
     */
    @SuppressWarnings("rawtypes")
    public static List<String> unZipFiles(File zipFile,String descDir)throws IOException
    {
        List<String> pathList = new ArrayList<>();
        File pathFile = new File(descDir);
        if(!pathFile.exists())
        {
            pathFile.mkdirs();
        }
        //解决zip文件中有中文目录或者中文文件
        try (ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"))) {
            for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
                ZipEntry entry = (ZipEntry)entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);
                String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
                //判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if(!file.exists())
                {
                    file.mkdirs();
                }
                //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if(new File(outPath).isDirectory())
                {
                    continue;
                }
                //输出文件路径信息
                System.out.println(outPath);
                pathList.add(outPath);
                OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[1024];
                int len;
                while((len=in.read(buf1))>0)
                {
                    out.write(buf1,0,len);
                }
                in.close();
                out.close();
            }
        }
        return pathList;
    }
    
    
    public static void folderToZip (String sourceDirPath, String zipFilePath, String zipFileName) throws IOException{
        File sourceFile = new File(sourceDirPath);
        if (!sourceFile.exists()) {
            throw new IOException("待压缩的文件目录:" + sourceDirPath + " 不存在.");
        }
        createDirs(zipFilePath);
        File zipFile = new File(zipFilePath + zipFileName);
        if (zipFile.exists() && !zipFile.delete()) {
            throw new IOException("删除已存在的文件:" + zipFilePath + zipFileName + " 异常.");
        }
        File[] sourceFiles = sourceFile.listFiles();
        if (sourceFiles == null || sourceFiles.length < 1) {
            throw new IOException("待压缩的文件目录:" + sourceDirPath + "为空文件夹.");
        }
        
        ZipOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            //创建zip输出流
            out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
            //调用压缩函数
            for(File file : sourceFiles) {
                compress(out, file, file.getName());
            }
            out.flush();
 
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOCloseUtil.close(bos, out);
        }
    }
 
    /**
     * 文件压缩
     * @param out
     * @param bos
     * @param sourceFile
     * @param base
     */
    public static void compress(ZipOutputStream out, File sourceFile, String base){
        FileInputStream fos = null;
        try {
            //如果路径为目录(文件夹)
            if (sourceFile.isDirectory()) {
                //取出文件夹中的文件(或子文件夹)
                File[] flist = sourceFile.listFiles();
                if (flist.length == 0) {//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
                    out.putNextEntry(new ZipEntry(base + "/"));
                } else {//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
                    for (int i = 0; i < flist.length; i++) {
                        compress(out, flist[i], base + "/" + flist[i].getName());
                    }
                }
            } else {//如果不是目录(文件夹),即为文件,将文件写入zip文件中
                out.putNextEntry(new ZipEntry(base));
                fos = new FileInputStream(sourceFile);
 
                int tag;
                //将源文件写入到zip文件中
                while ((tag = fos.read()) != -1) {
                    out.write(tag);
                }
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOCloseUtil.close(fos);
        }
    }



    /**
     * 创建多层级文件夹
     *
     * @param path
     * @return
     */
    private static boolean createDirs(String path) {
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            return fileDir.mkdirs();
        }
        return true;
    }
    
    public static void main(String[] args) throws IOException {
        String targetFilePath = "d://tmp/zipTest/zipTest.zip";
        String destFilePath = "d://tmp/zipTest/target/";
        //解压缩
        List<String> filePaths = unZipFiles(targetFilePath, destFilePath);
        System.out.println(JSONObject.toJSONString(filePaths));
        String zipFilePath = "d://tmp/zipTest/";
        String zipFileName = "zipTest1.zip";
        folderToZip(destFilePath, zipFilePath, zipFileName);
    }
}

IOCloseUtil:

package com.ly.mp.project.utils;

import java.io.Closeable;
import java.io.IOException;

public class IOCloseUtil {
    /**
     *   IO流关闭工具类
     */
    public static void close(Closeable... io) {
        for (Closeable temp : io) {
            try {
                if (null != temp)
                    temp.close();
            } catch (IOException e) {
                System.out.println("" + e.getMessage());
            }
        }
    }
 
    public static <T extends Closeable> void closeAll(T... io) {
        for (Closeable temp : io) {
            try {
                if (null != temp)
                    temp.close();
            } catch (IOException e) {
                System.out.println("" + e.getMessage());
            }
        }
 
    }
}

我们在D:\tmp\zipTest目录下面放置了一个zipTest.zip的测试文件,里面包含一个test文件夹和test.txt文件,test文件夹里面也包含一个test.txt文件。
我们新建了一个D:\tmp\zipTest\target\文件夹,期望结果是程序会把zipTest.zip解压到这个target文件夹里,然后会target文件夹里的所有文件和文件夹进行zip打包生成D:\tmp\zipTest\zipTest1.zip
运行上面的ZipTest里的main方法,可以得到以下打印结果:

d://tmp/zipTest/target/test/test.txt
d://tmp/zipTest/target/test.txt
["d://tmp/zipTest/target/test/test.txt","d://tmp/zipTest/target/test.txt"]

实测可以解压带文件夹的zip文件,目录结构也不会有影响,重新打包后的zipTest1.zip也正常。

相关文章

网友评论

      本文标题:java对带文件夹的文件实现zip压缩解压缩记录

      本文链接:https://www.haomeiwen.com/subject/ompjbdtx.html