JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

How To Create Zip File Using Java

April 21, 2014 by Krishna Srinivasan Leave a Comment

This example demonstrates how to create a zip file with the files and directories. Java provides java.util.zip package for compressing and packaging to zip file format. It is very common utility used by most of the applications. The key classes used in this package for packaging to zip format are ZipOutputStream, ZipEntry and Deflater. This example very well illustrates the packaging files and directories with path. Lets look at the example.

If you have any issues with the below code, please write it in the comments section. Note that, you have to provide the list of files and output file name for this program to work. I have added that code into the main method. Also read our previous articles working with java.util.zip and list contents from zip file.

CreateZipExample.java

[code lang=”java”]
package javabeat.net.zip;

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.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* Create ZIP Example
*
* @author Krishna
*
*/
public class CreateZipExample
{
public static void main(String[] args) throws IOException{
List files = new ArrayList();
files.add(new File("TextFile.txt"));
CreateZipExample.packageZipFile(new File("TestZip.zip"), files);
}

/**
* Packaging ZIP file
* @param output
* @param files
* @throws IOException
*/
public static void packageZipFile(File output, List files) throws IOException
{
System.out.println("Packaging To " + output.getName());

//Create ZipOutputStream to create Zip file
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(output));
zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

//Iterate the files and zipping it
for (File file : files)
{
if (file.isDirectory())
{
zipDirectory(zipOutputStream, "", file);
} else
{
zipFile(zipOutputStream, "", file);
}
}
zipOutputStream.flush();
zipOutputStream.close();
System.out.println("Zipping Done");
}

private static String buildPath(String filePath, String fileVar)
{
if (filePath == null || filePath.isEmpty())
{
return fileVar;
} else
{
return filePath + "/" + fileVar;
}
}

/**
* Zipping Directory
*
* @param zipOutStream
* @param filePath
* @param directory
* @throws IOException
*/
private static void zipDirectory(ZipOutputStream zipOutStream, String filePath, File directory) throws IOException
{
if (!directory.canRead())
{
System.out.println("Cannot read " + directory.getCanonicalPath() + " (maybe because of permissions)");
return;
}

File[] files = directory.listFiles();
filePath = buildPath(filePath, directory.getName());
System.out.println("Adding Directory " + filePath);

for (File source : files)
{
if (source.isDirectory())
{
zipDirectory(zipOutStream, filePath, source);
} else
{
zipFile(zipOutStream, filePath, source);
}
}

System.out.println("Leaving Directory " + filePath);
}

/**
* Zipping individual file
*
* @param zipOutStream
* @param filePath
* @param file
* @throws IOException
*/
private static void zipFile(ZipOutputStream zipOutStream, String filePath, File file) throws IOException
{
//Check if file can be read
if (!file.canRead())
{
System.out.println("Cannot read file : " + file.getCanonicalPath());
return;
}

System.out.println("Compressing File : " + file.getName());
zipOutStream.putNextEntry(new ZipEntry(buildPath(filePath, file.getName())));

FileInputStream fileInStream = new FileInputStream(file);

byte[] bufferVar = new byte[4092];
int byteVar = 0;
while ((byteVar = fileInStream.read(bufferVar)) != -1)
{
zipOutStream.write(bufferVar, 0, byteVar);
System.out.print(‘.’);
System.out.flush();
}
fileInStream.close();
zipOutStream.closeEntry();
}
}
[/code]

Filed Under: Java Tagged With: Java Zip

How To List Contents Of Zip File using Java

April 21, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to list the files inside a zip file. Zip is the most widely used utility for compressing the files and it is the Windows platform standard. In cases where you would need to work on the Zip file in Java for reading and writing into zip file. Here I write a simple example to print the number of entries in the zip file and how to list them.  We use the following API for this task.

  • java.util.zip.ZipFile – This API used for creating the ZIp file instance and reading it
  • java.util.zip.ZipEntry – This API holds the details of the each entry in the ZIp file

Lets look at the example on how to list the files inside zip file PrimeFaces-Collector.zip. This example first get the number of entries in the file using the size() method and then get the list of entries using the method entries().

ListFilesZipExample.java

[code lang=”java”]
package javabeat.net.zip;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
* List Zip File Example
*
* @author krishna
*
*/
public class ListFilesZipExample {
public static void main(String[] args) {
ZipFile zipFile = null;
try {
// Create ZipFile instance
zipFile = new ZipFile("PrimeFaces-Collector.zip");

// Get the zip entries
Enumeration<? extends ZipEntry> e = zipFile.entries();
int counter = 1;
System.out.println("Number of Entries : " + zipFile.size());
while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
// Get the entry
String entryName = entry.getName();
System.out.println("ZIP Entry " + counter + " : " + entryName);
counter++;
}

} catch (IOException ioe) {
System.out.println("Error opening zip file" + ioe);
} finally {
try {
if (zipFile != null) {
zipFile.close();
}
} catch (IOException ioe) {
System.out.println("Error while closing zip file" + ioe);
}
}

}

}
[/code]

Output…

[code]
Number of Entries : 50
ZIP Entry 1 : PrimeFaces-Collector/src/main/java/net/javabeat/primefaces/data/User.java
ZIP Entry 2 : PrimeFaces-Collector/src/main/java/net/javabeat/primefaces/RegistrationBean.java
ZIP Entry 3 : PrimeFaces-Collector/.metadata/src/main/webapp/WEB-INF/faces-config.pageflow
ZIP Entry 4 : PrimeFaces-Collector/src/main/webapp/resources/images/ajax-loader.gif
ZIP Entry 5 : PrimeFaces-Collector/src/main/webapp/resources/js/autocomplete.js
ZIP Entry 6 : PrimeFaces-Collector/src/main/webapp/WEB-INF/faces-config.xml
ZIP Entry 7 : PrimeFaces-Collector/src/main/webapp/WEB-INF/web.xml
ZIP Entry 8 : PrimeFaces-Collector/src/main/webapp/index.xhtml
ZIP Entry 9 : PrimeFaces-Collector/.settings/.jsdtscope
ZIP Entry 10 : PrimeFaces-Collector/.settings/org.codehaus.groovy.eclipse.core.prefs
ZIP Entry 11 : PrimeFaces-Collector/.settings/org.eclipse.core.resources.prefs
ZIP Entry 12 : PrimeFaces-Collector/.settings/org.eclipse.jdt.core.prefs
ZIP Entry 13 : PrimeFaces-Collector/.settings/org.eclipse.jdt.groovy.core.prefs
ZIP Entry 14 : PrimeFaces-Collector/.settings/org.eclipse.jpt.core.prefs
ZIP Entry 15 : PrimeFaces-Collector/.settings/org.eclipse.m2e.core.prefs
ZIP Entry 16 : PrimeFaces-Collector/.settings/org.eclipse.wst.common.component
ZIP Entry 17 : PrimeFaces-Collector/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml
ZIP Entry 18 : PrimeFaces-Collector/.settings/org.eclipse.wst.common.project.facet.core.xml
ZIP Entry 19 : PrimeFaces-Collector/.settings/org.eclipse.wst.jsdt.ui.superType.container
ZIP Entry 20 : PrimeFaces-Collector/.settings/org.eclipse.wst.jsdt.ui.superType.name
ZIP Entry 21 : PrimeFaces-Collector/.settings/org.eclipse.wst.validation.prefs
ZIP Entry 22 : PrimeFaces-Collector/.settings/org.scala-ide.sdt.core.prefs
ZIP Entry 23 : PrimeFaces-Collector/.cache
ZIP Entry 24 : PrimeFaces-Collector/.classpath
ZIP Entry 25 : PrimeFaces-Collector/.project
ZIP Entry 26 : PrimeFaces-Collector/pom.xml
ZIP Entry 27 : PrimeFaces-Collector/src/main/java/net/javabeat/primefaces/data/
ZIP Entry 28 : PrimeFaces-Collector/src/main/java/net/javabeat/primefaces/
ZIP Entry 29 : PrimeFaces-Collector/.metadata/src/main/webapp/WEB-INF/
ZIP Entry 30 : PrimeFaces-Collector/src/main/java/net/javabeat/
ZIP Entry 31 : PrimeFaces-Collector/src/main/webapp/resources/images/
ZIP Entry 32 : PrimeFaces-Collector/src/main/webapp/resources/js/
ZIP Entry 33 : PrimeFaces-Collector/src/main/webapp/resources/css/
ZIP Entry 34 : PrimeFaces-Collector/.metadata/src/main/webapp/
ZIP Entry 35 : PrimeFaces-Collector/src/main/java/net/
ZIP Entry 36 : PrimeFaces-Collector/src/main/webapp/resources/
ZIP Entry 37 : PrimeFaces-Collector/src/main/webapp/WEB-INF/
ZIP Entry 38 : PrimeFaces-Collector/.metadata/src/main/
ZIP Entry 39 : PrimeFaces-Collector/src/main/java/
ZIP Entry 40 : PrimeFaces-Collector/src/main/webapp/
ZIP Entry 41 : PrimeFaces-Collector/src/main/resources/
ZIP Entry 42 : PrimeFaces-Collector/src/test/java/
ZIP Entry 43 : PrimeFaces-Collector/src/test/resources/
ZIP Entry 44 : PrimeFaces-Collector/.metadata/src/
ZIP Entry 45 : PrimeFaces-Collector/src/main/
ZIP Entry 46 : PrimeFaces-Collector/src/test/
ZIP Entry 47 : PrimeFaces-Collector/.metadata/
ZIP Entry 48 : PrimeFaces-Collector/.settings/
ZIP Entry 49 : PrimeFaces-Collector/src/
ZIP Entry 50 : PrimeFaces-Collector/
[/code]

Filed Under: Java Tagged With: Java Zip

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved