2

I found an example on how to zip all the files in a folder but I would like to zip a whole folder, with all its subfolders and the files contained within all of them.

I am using groovy, so a Java solution is perfectly fine.

How can I zip a whole folder with its contents in groovy?

user3804769
  • 469
  • 1
  • 8
  • 19
  • What is your context? Is it a full groovy distributive (with ant) or just groovy-all lib? If you have ant - then you could use antbuilder.zip: http://docs.groovy-lang.org/latest/html/documentation/ant-builder.html – daggett Jun 06 '19 at 13:27
  • https://stackoverflow.com/questions/14225264/zip-files-directories-in-groovy-with-antbuilder – Jayan Jun 06 '19 at 14:37

5 Answers5

1

You can use Zeroturnaround Zip for this.

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

Adding this dependency

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

[UPDATED]

This is a way of doing it using Java 8 solution:

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);
    }
}

And then calling:

        AppZip appZip = new AppZip("/your/folder/here");
        appZip.zipIt("/your/zip/here");
Brother
  • 2,150
  • 1
  • 20
  • 24
  • Thank you! Since it's not a maven project, is there any way I could just download a jar or two and make it work? I'm running a simple groovy script, I don't have a Maven project. I tried importing the jar and it can't find the org/slf4j/LoggerFactory class when I run it. – user3804769 Jun 06 '19 at 13:05
1

Is this solution not a bit more groovy?

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()
}
lepe
  • 24,677
  • 9
  • 99
  • 108
ulrichenslin
  • 1,003
  • 1
  • 9
  • 8
  • Yes and does create my zip file containing the file, but i used PNGs and have a whole different problem with corrupt PNG so its not bullet proof and i havent tested it with other files. Hopefully i can get it working with PNGs as this method is way simpler – imp Sep 16 '20 at 15:05
  • @MistaWizard : The problem was in this line: `zos << file`, as it was storing the file name and not the actual data. I edited the answer. If you want sub-directories as well, look at my answer. – lepe Apr 28 '21 at 07:09
1

Based on @urichenslin's answer, here is one which works with sub-directories and solves the issue commented by @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
}
lepe
  • 24,677
  • 9
  • 99
  • 108
0

This is solution that zip all files (include subdirectories) from srcDir and save the result as 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()
}
Thomas.
  • 91
  • 2
  • 6
0

Modified the code for jedox groovy etl (apache tomcat), zips directory with sub-directories as they are.

fileSRC = /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()
}