Java压缩多层目录及文件

38 篇文章 1 订阅
    public static void main(String[] args) throws Exception {
        // 压缩目录D:\tmp\smf_storage\history下的所有内容到D:\tmp\smf_storage\bak20211230.zip
        compress("D:\\tmp\\smf_storage\\history", "D:\\tmp\\smf_storage\\bak20211230.zip");

        // 不指定目标路径,默认压缩目录D:\tmp\smf_storage\history下的所有内容到D:\tmp\smf_storage\history.zip
        compress("D:\\tmp\\smf_storage\\history", null);
    }

    /**
     * <一句话功能简述> 压缩文件夹内容
     * <功能详细描述> 
     * author: zhanggw
     * 创建时间:  2021/12/30
     * @param targetDir 压缩文件夹目录全路径
     * @param compressFilePath zip压缩包存储路径,null表示保存在父级目录下,文件名为targetDir的最后名称+".zip"
     */
    public static void compress(String targetDir, String compressFilePath){
        try{
            File sourceFile = new File(targetDir);
            if(StringUtils.isBlank(compressFilePath)){
                compressFilePath = sourceFile.getParentFile().getAbsolutePath() + File.separator + sourceFile.getName() + ".zip";
            }
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(compressFilePath));
            compress(sourceFile, sourceFile.getName(), zipOutputStream);
            zipOutputStream.close();
        }catch (Exception e){
            logger.error("压缩文件异常!", e);
        }
    }

    /**
     * <一句话功能简述> 递归压缩zip
     * <功能详细描述> 
     * author: zhanggw
     * 创建时间:  2021/12/30
     * @param sourceDir 压缩目标目录
     * @param zipDirName zip压缩包中当前目录名称  history/fund
     * @param targetZipOut zip压缩包输出流
     */
    private static void compress(File sourceDir, String zipDirName, ZipOutputStream targetZipOut){
        if(!sourceDir.exists()){
            logger.debug("待压缩的目录"+sourceDir.getName()+"不存在");
            return;
        }

        File[] files = sourceDir.listFiles();
        if(files == null || files.length ==0){
            return;
        }

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        byte[] byteArray = new byte[1024*10];

        try{
            for (File file : files) {
                if (file.isFile()) {
                    logger.debug("开始压缩:{}", file.getAbsoluteFile());
                    ZipEntry zipEntry = new ZipEntry(zipDirName + File.separator + file.getName());
                    targetZipOut.putNextEntry(zipEntry);
                    //读取待压缩的文件并写进压缩包里
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis, 1024 * 10);
                    int read;
                    while ((read = bis.read(byteArray, 0, 1024 * 10)) != -1) {
                        targetZipOut.write(byteArray, 0, read);
                    }
                    //如果需要删除源文件,则需要执行下面2句
                    //fis.close();
                    //fs[i].delete();
                } else if (file.isDirectory()) {
                    logger.debug("进入目录:{}", file.getAbsoluteFile());
                    compress(file, zipDirName + File.separator + file.getName(), targetZipOut);
                }
            }//end for
        }catch  (IOException e) {
            logger.error("打包异常!",e);
        } finally{
            //关闭流
            try {
                if(null!=bis) bis.close();
                if(null!=fis) fis.close();
            } catch (IOException e) {
                logger.error("打包关闭流异常!",e);
            }
        }
    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: Java可以使用ZipInputStream类来解压缩zip文件。如果要解压多层zip包,可以在读取每个zip包的内容之前先判断它是否还是一个zip包,如果是则继续解压缩。 以下是一个解压多层zip包的示例代码: ```java import java.io.*; import java.util.zip.*; public class Unzip { public static void main(String[] args) throws IOException { String zipFilePath = "path/to/multilayer.zip"; String destDirPath = "path/to/destination/folder"; unzip(zipFilePath, destDirPath); } public static void unzip(String zipFilePath, String destDirPath) throws IOException { File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { String entryName = entry.getName(); String filePath = destDirPath + File.separator + entryName; if (entry.isDirectory()) { File dir = new File(filePath); dir.mkdir(); } else { 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(); } zipIn.closeEntry(); if (entryName.endsWith(".zip")) { // unzip nested zip file unzip(filePath, destDirPath); // delete the nested zip file File nestedZipFile = new File(filePath); nestedZipFile.delete(); } entry = zipIn.getNextEntry(); } zipIn.close(); } } ``` 在上面的代码中,`unzip`方法接收两个参数:zip文件路径和目标文件路径。首先创建目标文件,然后创建ZipInputStream对象并循环读取每个ZipEntry。如果ZipEntry是一个目录,则创建一个目录。如果ZipEntry是一个文件,则将其内容写入到文件中。如果ZipEntry是一个zip文件,则递归调用`unzip`方法解压缩它,并在解压缩完成后删除该文件。最后关闭ZipInputStream对象。 ### 回答2: Java解压多层zip包可以通过使用Java的ZipInputStream类来实现。下面是一个简单的示例代码: ```java import java.io.*; import java.util.zip.*; public class UnzipMultiLayeredZip { public static void main(String[] args) { String zipFilePath = "path/to/multilayered.zip"; String destFolderPath = "path/to/destination/folder"; try { unzip(zipFilePath, destFolderPath); System.out.println("解压多层zip包成功!"); } catch (IOException e) { System.out.println("解压多层zip包失败: " + e.getMessage()); } } public static void unzip(String zipFilePath, String destFolderPath) throws IOException { File destFolder = new File(destFolderPath); if (!destFolder.exists()) { destFolder.mkdirs(); } FileInputStream fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); byte[] buffer = new byte[1024]; ZipEntry entry = zis.getNextEntry(); while (entry != null) { String entryName = entry.getName(); String entryPath = destFolderPath + File.separator + entryName; if (entry.isDirectory()) { new File(entryPath).mkdirs(); } else { FileOutputStream fos = new FileOutputStream(entryPath); int bytesRead; while ((bytesRead = zis.read(buffer)) > 0) { fos.write(buffer, 0, bytesRead); } fos.close(); } zis.closeEntry(); entry = zis.getNextEntry(); } zis.close(); fis.close(); } } ``` 上述代码中使用了ZipInputStream类来读取zip文件,并通过ZipEntry对象获取每个压缩项的信息。如果压缩项是一个文件,就创建相应的文件;如果是文件,则通过FileOutputStream将文件写入目标文件中。 要解压多层zip包,只需要递归地调用unzip方法,传入嵌套zip文件的路径和目标文件路径即可。 请确保将示例代码中的"path/to/multilayered.zip"替换为你想要解压的多层zip包的实际路径,将"path/to/destination/folder"替换为你想要解压到的目标文件的实际路径。 ### 回答3: 在Java中解压多层zip包可以使用Java标准库提供的ZipInputStream类。ZipInputStream类可以用来从压缩文件中读取条目,并将其解压缩到指定的目录或输出流中。 首先,我们需要打开最外层的压缩文件,并创建一个ZipInputStream对象来读取它。然后,我们可以使用getNextEntry()方法逐个读取压缩文件中的条目。 如果当前条目是一个目录,我们可以使用File类来创建相应的目录。然后,我们可以继续读取下一个条目。 如果当前条目是一个文件,我们可以使用BufferedOutputStream将其内容写入到指定的目录或输出流中。我们可以指定解压缩后的文件名和路径,通过File类来创建相应的文件。 除了解压缩文件中的条目外,我们还需要处理多层zip包的情况。如果某个条目是一个zip文件,我们可以递归地调用解压缩函数来解压缩该zip文件。这样,我们就可以解压多层zip包了。 最后,在解压完所有的条目后,我们需要调用close()方法关闭ZipInputStream对象和相关的输入流。这样可以释放资源并避免内存泄漏。 在解压多层zip包时,务必要注意文件名和路径的处理,以保证解压后的文件结构正确。另外,要对异常情况进行适当的处理和错误提示,以提高代码的健壮性和用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kenick

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值