Friday, August 7, 2015

Creation of zip file using Java

I want to show how we can create a Zip file in this post.

I am going to use a classes called ZipEntry and ZipOutputStream which are part of java.util.zip.

ZipEntry is used to create a zip file and ZipOutputStream takes data in an output stream and encloses the files in a zip.

I am reading the data from File Input Stream and writing to Zip Output Stream.

Reading count from file input stream and creating a byte of same size to accommodate the byte with file data and write to zip output stream.

I am writing data to File Output Stream and passing the File Output Stream instance variable as parameter to Zip Output Stream for the zip file to be created.

After writing data to zip file, we have to close the zip output stream and file output stream.

Check the below code for creating zip files using Java.


 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.util.zip.ZipEntry;  
 import java.util.zip.ZipOutputStream;  
 public class TestClass {  
      /**  
       * @param args  
       * @throws IOException  
       */  
      public static void main(String[] args) throws IOException {  
           String textFileName = "F:/abc.txt";  
           String zipFileName = "F:/createdFile.zip";  
           File textFile = new File(textFileName);  
           File zipFile = new File(zipFileName);  
           FileInputStream fiStream = new FileInputStream(textFile);  
           FileOutputStream foStream = new FileOutputStream(zipFile);  
           int count = fiStream.read();  
           byte[] bytes = new byte[count];  
           ZipEntry zipEntry = new ZipEntry(textFileName);  
           if (!zipFile.exists()) {  
                zipFile.createNewFile();  
           }  
           ZipOutputStream zoStream = new ZipOutputStream(foStream);  
           zos.putNextEntry(zipEntry);  
           while ((count = fis.read(bytes)) >= 0) {  
                zoStream.write(bytes, 0, count);  
           }  
           fiStream.close();  
           zoStream.closeEntry();  
           zoStream.close();  
           foStream.close();  
      }  
 }  

No comments:

Comments

blog comments powered by Disqus