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
  • Contact Us

Compress Files To ZIP Format Using Java

January 25, 2014 by Krishna Srinivasan Leave a Comment

This post demonstrates a simple example for how to compress your file and add to the ZIP file. Java has built-in API java.util.zip for compressing the files in ZIP format. It is very simple to read the files from your disk and writing to the destination ZIP file. It is straight forward.  The steps involved for writing to ZIP is:

  1. Read files using FileInputStream
  2. Then add the files to ZipEntry which is used for adding the list of files which are part of zip file
  3. Finally output the zip file by using the ZipOutputStream class

Lets look at the example:

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

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

public class CompressZipExample {

public static void main(String[] args) {
byte[] buffer = new byte[1024];

try {
FileOutputStream fileOutput = new FileOutputStream("SampleFile.zip");
ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

//Add a file entry to zip
ZipEntry zipEntry = new ZipEntry("TestFile.txt");
zipOutput.putNextEntry(zipEntry);

//Read the file from the given path
FileInputStream fileInput = new FileInputStream("TestFile.txt");

int length;
while ((length = fileInput.read(buffer)) > 0) {
zipOutput.write(buffer, 0, length);
}
fileInput.close();
zipOutput.closeEntry();
zipOutput.close();
System.out.println("Files are added to zip!!");
} catch (IOException ex) {
ex.printStackTrace();
}
}

}
[/code]

Filed Under: Java Tagged With: Java Basics, Java File IO

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

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