首页 > 编程语言 > 详细

Java工具类-zip文件解压缩

时间:2021-03-12 15:18:07      阅读:19      评论:0      收藏:0      [点我收藏+]

功能

将zip文件解压到指定目录下(注意:不支持zip内文件名或文件夹名包含中文)。

代码

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author :kzhu
 * @version :1.0
 * @date :Created in 2021/3/12 11:28
 * @description :
 * @modified By:
 */
public class FileUtil {


    /**
     * 解压zip文件到指定目录
     *
     * @param inputFile   需要压缩的文件路径
     * @param destDirPath 指定保存的目录路径
     * @throws Exception
     */
    public static void unZipFile(String inputFile, String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));
        ZipEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(destDirPath, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序,先打开的后关闭
                bos.close();
                out.close();
            }
        }
    }


}

测试

测试代码:

    @Test
    void unZipFile() {
        try {
            FileUtil.unZipFile("D:/Kevin/TODO/UnZipTest/testfile.zip", "D:/Kevin/TODO/UnZipTest/TargetFolder");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

结果:
技术分享图片
技术分享图片

Java工具类-zip文件解压缩

原文:https://www.cnblogs.com/kevinchu1998/p/14523228.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!