java 实现zip 压缩 解压 (目录控制)

简介: java 实现zip 压缩 解压 (目录控制)

直接上代码

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
//zip操作
public class ZipDemo {
    //目录名称
    private static String driName =null;
    //压缩后是否包含最外层的目录 
    private static Boolean delOutside = false;
    public static String getDriName() {
        return driName;
    }
    public static void setDriName(String driName) {
        ZipDemo.driName = driName;
    }
    public static Boolean getDelOutside() {
        return delOutside;
    }
    public static void setDelOutside(Boolean delOutside) {
        ZipDemo.delOutside = delOutside;
    }
    /**
     * 压缩
     * @param outFile 文件输出的地址
     * @param targetFile 需要压缩的目录
     * @param isDelOutside 压缩后是否包含最外层的目录 true 包含 false 不包含
     */
    private static void compression(String outFile, File targetFile,Boolean isDelOutside) {
        System.out.println("压缩进行中");
        long start = System.currentTimeMillis();
        delOutside = isDelOutside;
        BufferedOutputStream bos = null;
        try {
            if (!targetFile.exists()) {
                System.out.println("文件地址不存在");
                return;
            }
            ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(outFile));
            bos = new BufferedOutputStream(zOut);
            driName = targetFile.getName();
            zip(zOut, targetFile, driName, bos);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("压缩完成,耗时:" + (end - start) + " ms");
        System.out.println("压缩完成");
    }
    private static void zip(ZipOutputStream zOut, File targetFile, String name, BufferedOutputStream bos) throws IOException {
        if (targetFile.isDirectory()) {
            File[] files = targetFile.listFiles();
            //判断是否为空目录
            if (files.length == 0) {
                zOut.putNextEntry(new ZipEntry(name + "/"));
            } else {
                //目录递归调用
                for (File file : files) {
                    zip(zOut, file, name + "/" + file.getName(), bos);
                }
            }
        } else {
            if(!delOutside){
                name = name.replaceFirst(driName+"/","");
            }
            zOut.putNextEntry(new ZipEntry(name));
            InputStream in = new FileInputStream(targetFile);
            BufferedInputStream bis = new BufferedInputStream(in);
            //将源文件写入到zip文件中
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            bis.close();
        }
    }
    //解压
    private static void decompression(String targetFileName, String parent) {
        try {
            File targetFile = new File(targetFileName);
            if(!targetFile.exists()){
                System.out.println("文件地址不存在");
            }
            ZipInputStream zis = new ZipInputStream(new FileInputStream(targetFile));
            ZipEntry entry = null;
            File file = null;
            while ((entry = zis.getNextEntry()) != null && !entry.isDirectory()) {
                file = new File(parent, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                int len = -1;
                byte[] bytes = new byte[1024];
                while ((len = zis.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                }
                System.out.println(file.getAbsoluteFile() + "解压完成");
                bos.close();
            }
            System.out.println("解压结束");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) {
        //压缩调用
        compression("F:\\1.zip", new File("F:\\测试"),true);
        //解压调用
//        decompression("F:\\1.zip", "F:\\测试\\");
    }
}

注意点

压缩的方法有一个isDelOutside参数,是用来控制是否将最外层的目录压缩进去的。

例如:

目录结构

8.png

isDelOutside=true时,包含最外层的目录

9.png

isDelOutside=true时,不包含最外层的目录

10.png

相关文章
|
3月前
|
分布式计算 Java Hadoop
linux中HADOOP_HOME和JAVA_HOME删除后依然指向旧目录
通过以上步骤,可以有效地解决 `HADOOP_HOME`和 `JAVA_HOME`删除后依然指向旧目录的问题。确保在所有相关的配置文件中正确设置和删除环境变量,并刷新当前会话,使更改生效。通过这些措施,能够确保系统环境变量的正确性和一致性。
45 1
|
3月前
|
存储 Java API
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
146 4
|
4月前
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
142 5
|
5月前
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
158 2
|
5月前
|
存储 缓存 监控
Java——图片文件位于 bin 目录下,下载新图片会导致应用程序重启
【9月更文挑战第22天】在Java应用中,若图片位于bin目录下且下载新图片导致应用重启,可能是因为部署方式不当或资源监控机制过于敏感。解决方法包括:更改图片存储位置至独立目录;配置应用服务器减少资源监控敏感度;使用独立资源服务器托管静态资源;优化代码减少资源重复加载。具体方案需根据应用实际情况和技术栈调整。
|
5月前
|
算法 Java
Java 压缩文件
在Java中压缩文件是一个常见的需求,通常可以通过使用Java自带的`java.util.zip`包来实现。这个包提供了`ZipOutputStream`类来创建ZIP格式的压缩文件。以下是一个简单的示例,展示了如何将多个文件压缩到一个ZIP文件中。 ### 示例:将多个文件压缩到一个ZIP文件中 ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFilesExample { public static vo
|
消息中间件 前端开发 JavaScript
如何用Java实现文件压缩和解压缩?
PS:最近是跳槽的高峰期,我连日加班好多天,整理出了包含16000 多道面试题的面试宝典,并且指北君也会持续更新这份面试宝典中的题目,希望它能帮助大家找到自己心仪的工作!【文末有领取方式】
如何用Java实现文件压缩和解压缩?
|
1月前
|
监控 Java
java异步判断线程池所有任务是否执行完
通过上述步骤,您可以在Java中实现异步判断线程池所有任务是否执行完毕。这种方法使用了 `CompletionService`来监控任务的完成情况,并通过一个独立线程异步检查所有任务的执行状态。这种设计不仅简洁高效,还能确保在大量任务处理时程序的稳定性和可维护性。希望本文能为您的开发工作提供实用的指导和帮助。
95 17
|
2月前
|
Java
Java—多线程实现生产消费者
本文介绍了多线程实现生产消费者模式的三个版本。Version1包含四个类:`Producer`(生产者)、`Consumer`(消费者)、`Resource`(公共资源)和`TestMain`(测试类)。通过`synchronized`和`wait/notify`机制控制线程同步,但存在多个生产者或消费者时可能出现多次生产和消费的问题。 Version2将`if`改为`while`,解决了多次生产和消费的问题,但仍可能因`notify()`随机唤醒线程而导致死锁。因此,引入了`notifyAll()`来唤醒所有等待线程,但这会带来性能问题。
Java—多线程实现生产消费者
|
1月前
|
缓存 安全 算法
Java 多线程 面试题
Java 多线程 相关基础面试题