Java解压zip文件(支持对文件夹解压/压缩)

该方法不用引入外部包

  • 工具类ZipUtils:
import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;

public class ZipUtils {

    /**
     * 压缩文件/文件夹
     * 
     */
    public static void compress(String srcFilePath, String destFilePath) {
        File src = new File(srcFilePath);
        if (!src.exists()) {
            throw new RuntimeException(srcFilePath + "不存在");
        }
        File zipFile = new File(destFilePath);
        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());
            ZipOutputStream zos = new ZipOutputStream(cos);
            String baseDir = "";
            compressbyType(src, zos, baseDir);
            zos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void compressbyType(File src, ZipOutputStream zos, String baseDir) {
        if (!src.exists())
            return;
        System.out.println("压缩" + baseDir + src.getName());
        if (src.isFile()) {
            compressFile(src, zos, baseDir);
        } else if (src.isDirectory()) {
            compressDir(src, zos, baseDir);
        }
    }


    /**
     * 压缩文件
     */
    private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
        if (!file.exists())
            return;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zos.putNextEntry(entry);
            int count;
            byte[] buf = new byte[8019];
            while ((count = bis.read(buf)) != -1) {
                zos.write(buf, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }


    /**
     * 压缩文件夹
     * 
     */
    private static void compressDir(File dir, ZipOutputStream zos, String baseDir) {
        if (!dir.exists())
            return;
        File[] files = dir.listFiles();
        if(files.length == 0){
            try {
                zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for (File file : files) {
            compressbyType(file, zos, baseDir + dir.getName() + File.separator);
        }
    }


    /**
     * 解压文件/文件夹
     */
    public static void decompress(String srcPath, String dest) throws Exception {
        File file = new File(srcPath);
        if (!file.exists()) {
            throw new RuntimeException(srcPath + "所指文件不存在");
        }
        ZipFile zf = new ZipFile(file);
        Enumeration entries = zf.entries();
        ZipEntry entry = null;
        while (entries.hasMoreElements()) {
            entry = (ZipEntry) entries.nextElement();
            System.out.println("解压" + entry.getName());
            if (entry.isDirectory()) {
                String dirPath = dest + File.separator + entry.getName();
                File dir = new File(dirPath);
                dir.mkdirs();
            } else {
                // 表示文件
                File f = new File(dest + File.separator + entry.getName());
                if (!f.exists()) {
                    //String dirs = FileUtils.getParentPath(f);
                    String dirs = f.getParent();
                    File parentDir = new File(dirs);
                    parentDir.mkdirs();
                }
                f.createNewFile();
                // 将压缩文件内容写入到这个文件中
                InputStream is = zf.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(f);
                int count;
                byte[] buf = new byte[8192];
                while ((count = is.read(buf)) != -1) {
                    fos.write(buf, 0, count);
                }
                is.close();
                fos.close();
            }
        }
    }
}

测试类

  @RequestMapping("zip")
    public void testzip() {
        //压缩
           ZipUtils.compress("F:\\test","F:\\test.zip");
        ///解压
        try {
            ZipUtils.decompress("F:\\test.zip","F:\\as");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("解压文件夹失败");
        }
    }

Java编程思想中提到:压缩文件的时候,ZipOutputStream调用putNextEntry方法,并传入一个ZipEntry参数;解压文件的时候,new一个ZipFile对象并调用其entries()方法,对该方法返回的枚举类进行遍历并作为参数传给ZipFile的getInputStream方法。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用Java中的ZipInputStream和FileOutputStream来解压zip文件到当前文件夹。以下是一个简单的示例代码: ```java import java.io.*; import java.util.zip.*; public class UnzipFile { public static void main(String[] args) throws IOException { String zipFilePath = "example.zip"; String destDirectory = "./"; // 创建解压目录 File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } // 创建ZipInputStream对象 ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); // 读取Zip文件中的所有条目 ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { // 如果是文件解压文件 extractFile(zipIn, filePath); } else { // 如果是目录,创建目录 File dir = new File(filePath); dir.mkdir(); } // 关闭当前条目并定位到下一个条目 zipIn.closeEntry(); entry = zipIn.getNextEntry(); } // 关闭ZipInputStream zipIn.close(); } private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); } bos.close(); } } ``` 在此代码中,我们打开一个ZipInputStream对象并读取zip文件中的所有条目。如果一个条目是文件,我们调用`extractFile`方法来解压文件到当前文件夹。如果一个条目是目录,我们创建一个目录。最后,我们关闭ZipInputStream对象。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值