Groovy -如何在Groovy中压缩整个目录?

42fyovps  于 2022-11-01  发布在  其他
关注(0)|答案(5)|浏览(296)

我找到了an example on how to zip all the files in a folder,但我想压缩整个文件夹,所有的子文件夹和文件包含在所有这些文件夹。
我使用的是groovy,所以Java解决方案是非常好的。
如何在groovy中压缩整个文件夹及其内容?

ht4b089n

ht4b089n1#

您可以使用Zeroturnaround Zip来执行此操作。

ZipUtil.pack(new File("/your/folder/here"), new File("/your/zip/here.zip"));

正在添加此依赖项

<dependency>
  <groupId>org.zeroturnaround</groupId>
  <artifactId>zt-zip</artifactId>
  <version>1.13</version>
  <type>jar</type>
</dependency>

[已更新]
这是使用Java 8解决方案实现此目的的一种方法:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class AppZip {

    private List<String> fileList;
    private String sourceFolder;

    AppZip(String sourceFolder) {
        this.sourceFolder = sourceFolder;
        fileList = new ArrayList<>();
    }

    /**
     * Zip it
     *
     * @param zipFile output ZIP file location
     */
    public void zipIt(String zipFile) {

        byte[] buffer = new byte[1024];

        try {
            generateFileList(new File(sourceFolder));

            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            for (String file : this.fileList) {

                ZipEntry ze = new ZipEntry(file);
                zos.putNextEntry(ze);

                FileInputStream fin =
                        new FileInputStream(sourceFolder + File.separator + file);

                int len;
                while ((len = fin.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }

                fin.close();
            }

            zos.closeEntry();
            zos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Traverse a directory and get all files,
     * and add the file into fileList
     *
     * @param node file or directory
     */
    public void generateFileList(File node) {

        //add file only
        if (node.isFile()) {
            fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
        }

        if (node.isDirectory()) {
            String[] subNote = node.list();
            for (String filename : subNote) {
                generateFileList(new File(node, filename));
            }
        }

    }

    /**
     * Format the file path for zip
     *
     * @param file file path
     * @return Formatted file path
     */
    private String generateZipEntry(String file) {
        return file.substring(sourceFolder.length() + 1);
    }
}

然后喊:

AppZip appZip = new AppZip("/your/folder/here");
        appZip.zipIt("/your/zip/here");
4dbbbstv

4dbbbstv2#

根据@urichenslin的回答,下面是一个可以处理子目录并解决@MistaWizard所评论的问题的方法:

static File compress(final File srcDir, final File zipFile) {
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))
    srcDir.eachFileRecurse({
        zos.putNextEntry(new ZipEntry(it.path - srcDir.path + (it.directory ? "/" : "")))
        if(it.file) { zos << it.bytes }
        zos.closeEntry()
    })
    zos.close()
    return zipFile
}
w8biq8rn

w8biq8rn3#

这个解决方案是不是更时髦一点?

def zipDir(srcDir, zipFile) {
    def dir = new File(srcDir)
    def files = []
    dir.eachFileRecurse(groovy.io.FileType.FILES) { file ->
        files << file
    }

    FileOutputStream fos = new FileOutputStream(zipFile)
    def zos = new java.util.zip.ZipOutputStream(fos)

    for (file in files) {
        zos.putNextEntry(new java.util.zip.ZipEntry(file.path.minus(srcDir)))
        zos << file.bytes
        zos.closeEntry()
    }

    // close the ZipOutputStream
    zos.close()
}
vfwfrxfs

vfwfrxfs4#

这是一个从srcDir压缩所有文件(包括子目录)并将结果保存为zipFile的解决方案。

static void compress(File srcDir, File zipFile) {
    def output = new ZipOutputStream(new FileOutputStream(zipFile))
    output.setLevel(Deflater.BEST_COMPRESSION) //Use what you need

    srcDir.eachFileRecurse(groovy.io.FileType.FILES) {
        def name = (it.path - srcDir).substring(1)
        output.putNextEntry(new ZipEntry(name))
        output.write(it.bytes)
        output.closeEntry()
    }

    output.close()
}
epfja78i

epfja78i5#

修改了jedox groovy etl(apache tomcat)的代码,将目录与子目录保持原样。
fileTAR = /C:\\Users\\admin\\Downloads\\test\\sample\\files/
fileTAR = /C:\\Users\\admin\\Downloads\\test\\sample\\files/
zip()

def zip(srcDir = fileSRC, zipFile = fileTAR) {

    FileOutputStream fos = new FileOutputStream(new File(zipFile + '.zip'))
    def zos = new java.util.zip.ZipOutputStream(fos)

    new File(srcDir).eachFileRecurse() { file ->
      //drop the last slash
      filePathName = file.absolutePath.replaceAll(fileSRC,"")[1..-1]

        if (file.isFile()){
            zos.putNextEntry(new java.util.zip.ZipEntry(filePathName))
              zos << file.bytes
        } else {
            zos.putNextEntry(new java.util.zip.ZipEntry(filePathName + "/"))
        }    
        zos.closeEntry()
    }
    zos.close()
}

相关问题