www.thinkcode.se Open in urlscan Pro
54.73.26.109  Public Scan

URL: http://www.thinkcode.se/blog/2015/08/21/packaging-a-zip-file-from-java-using-apache-commons-compress
Submission: On April 19 via manual from US — Scanned from DE

Form analysis 0 forms found in the DOM

Text Content

Think Code AB
 * Offerings
 * Clients
 * Automation calculator
 * Blog
 * About






PACKAGING A ZIP FILE FROM JAVA USING APACHE COMMONS COMPRESS

Filed under: Java, Programming, — Tags: Gradle, org.apache.commons.compress, zip
— Thomas Sundberg — 2015-08-21

How do you create a zip file with Java? One option is to use Apache Commons
Compress.

This example shows you how.

I use Gradle to define dependencies needed as well as building the example.

The files needed are these:

example
|-- build.gradle
`-- src
    `-- test
        |-- java
        |   `-- se
        |       `-- thinkcode
        |           `-- zip
        |               `-- ZipFileTest.java
        `-- resources
            `-- readme.txt


Three different files.


PROJECT FILE

Create a Gradle project file with this content:

build.gradle

apply plugin: "java"

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.apache.commons:commons-compress:1.9'
    compile 'commons-io:commons-io:2.4'

    testCompile 'junit:junit:4.12'
}


This defines the dependencies I use. Most notably
org.apache.commons:commons-compress:1.9 that will do the heavy lifting.


THE IMPLEMENTATION

The implementation is then done in a test class. I am a fan of test driven
development so I wrote a test that will package the content of a directory and
then verify that one file was packed.

It looks like this:

src/test/java/se/thinkcode/zip/ZipFileTest.java

package se.thinkcode.zip;

import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.*;
import java.util.Collection;
import java.util.Enumeration;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

public class ZipFileTest {

    @Test
    public void add_all_files_from_a_directory_to_a_zip_archive() throws Exception {
        File source = new File("build/resources/test");
        File destination = new File("build/resources.zip");
        destination.delete();

        addFilesToZip(source, destination);

        assertTrue("Expected to find the zip file ", destination.exists());
        assertZipContent(destination);
    }

    /**
     * Add all files from the source directory to the destination zip file
     *
     * @param source      the directory with files to add
     * @param destination the zip file that should contain the files
     * @throws IOException      if the io fails
     * @throws ArchiveException if creating or adding to the archive fails
     */
    private void addFilesToZip(File source, File destination) throws IOException, ArchiveException {
        OutputStream archiveStream = new FileOutputStream(destination);
        ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream);

        Collection<File> fileList = FileUtils.listFiles(source, null, true);

        for (File file : fileList) {
            String entryName = getEntryName(source, file);
            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
            archive.putArchiveEntry(entry);

            BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));

            IOUtils.copy(input, archive);
            input.close();
            archive.closeArchiveEntry();
        }

        archive.finish();
        archiveStream.close();
    }

    /**
     * Remove the leading part of each entry that contains the source directory name
     *
     * @param source the directory where the file entry is found
     * @param file   the file that is about to be added
     * @return the name of an archive entry
     * @throws IOException if the io fails
     */
    private String getEntryName(File source, File file) throws IOException {
        int index = source.getAbsolutePath().length() + 1;
        String path = file.getCanonicalPath();

        return path.substring(index);
    }

    private void assertZipContent(File destination) throws IOException {
        ZipFile zipFile = new ZipFile(destination);

        ZipArchiveEntry readme = zipFile.getEntry("readme.txt");
        assertNotNull(readme);

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        int numberOfEntries = 0;
        while (entries.hasMoreElements()) {
            numberOfEntries++;
            entries.nextElement();
        }
        assertThat(numberOfEntries, is(1));
    }
}


The work is done in addFilesToZip.

I like the idea of Tdd as if you meant it and this was the result from my
implementation. Your job, if you want to use this solution, is to extract the
methods needed and possibly modify them to suit you needs.


BUILDING

Building this project requires you to have Gradle installed. When you have
installed a modern version of Gradle, 2.6 when this is written, you build the
example by executing

    gradle test


in the same directory as you have build.gradle. The dependencies needed will be
downloaded and the test that packages one file will be executed.


RESOURCES

 * Apache Commons Compress - an open source compression library
 * Gradle - a build tool for Java
 * Thomas Sundberg - The author



(less...)




Please enable JavaScript to view the comments powered by Disqus.

PAGES

About
Events
Why


CATEGORIES

Agile
Automation
BDD
Clean code
Continuous delivery
Continuous deployment
Continuous integration
Cucumber
Culture
Design
DevOps
Executable specification
Git
Gradle
Guice
J2EE
JUnit
Java
Javascript
Kubernetes
Linux
Load testing
Maven
Mockito
New developers
Pair programming
PicoContainer
Presentation
Programming
Public speaking
Quality
React
Recruiting
Requirements
Scala
Selenium
Software craftsmanship
Software development
Spring
TDD
Teaching
Technical debt
Test automation
Tools
Web
Windows
eXtreme Programming


AUTHORS

Thomas Sundberg
Adrian Bolboaca


ARCHIVES

Select Month April 2020 March 2020 February 2020 January 2020 December 2019
November 2019 October 2019 July 2019 May 2019 April 2019 March 2019 February
2019 January 2019 June 2018 May 2018 April 2018 March 2018 February 2018 January
2018 December 2017 October 2017 September 2017 August 2017 July 2017 June 2017
May 2017 April 2017 March 2017 February 2017 January 2017 December 2016 November
2016 October 2016 September 2016 August 2016 July 2016 June 2016 April 2016
March 2016 February 2016 January 2016 December 2015 November 2015 October 2015
September 2015 August 2015 July 2015 June 2015 April 2015 March 2015 February
2015 January 2015 December 2014 November 2014 October 2014 September 2014 August
2014 July 2014 June 2014 May 2014 April 2014 March 2014 February 2014 January
2014 December 2013 November 2013 October 2013 September 2013 July 2013 June 2013
May 2013 April 2013 March 2013 February 2013 January 2013 December 2012 November
2012 October 2012 September 2012 August 2012 July 2012 June 2012 May 2012 April
2012 March 2012 February 2012 January 2012 December 2011 November 2011 October
2011 September 2011 August 2011 July 2011 June 2011 May 2011 April 2011 March
2011 February 2011 January 2011 December 2010 July 2010 May 2010 January 2010
August 2009 April 2009

META

RSS

 

 

thomas@thinkcode.se

Definition of done: Working software, in production.

© Think Code AB