How to create a zip file


This code example shows how to create a zip file.
What we do is to create an input stream from the file we want to compress, and while we read from it we write the contents to an output stream.
This output stream is of type ZipOutputStream which takes an FileOutputStream as parameter.
Next we have to add a zip entry to the output stream before we start writing to it.
We will also clean up by closing the zip entry and both the input stream and output stream when we are done.


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

/**
 *
 * @author javadb.com
 */

public class Main {

    /**
     * Creates a zip file
     */

    public void createZipFile() {
        
        try {
            String inputFileName = "test.txt";
            String zipFileName = "compressed.zip";
            
            //Create input and output streams
            FileInputStream inStream = new FileInputStream(inputFileName);
            ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            
            // Add a zip entry to the output stream
            outStream.putNextEntry(new ZipEntry(inputFileName));
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            
            //Each chunk of data read from the input stream
            //is written to the output stream
            while ((bytesRead = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, bytesRead);
            }

            //Close zip entry and file streams
            outStream.closeEntry();

            outStream.close();
            inStream.close();
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().createZipFile();
    }
    
}

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: