Creating ZIP files
by, 11-12-2011 at 06:49 PM (1552 Views)
We all use ZIP files in daily routine. They are of great use specially when we want to transfer the files over the network. In this post, I will write about how to create zip files in Java.
Java.util.zip package provides classes to play with zip files. So first step is to import the package. We will need ZipOutputStream and ZipEntry class from this package. Import the complete package or just these classes - it depends on you. It does not have any affect on the performance.
I user to create a simple FileOutputStream zip file. It does not have any contents. I then created a ZipOutputStream using already created FileOutputStream. ZipEntry object is then created by specifying the file that is to be zipped. Now is the need to move the contents of file in to byte array. This was done using FileInputStream. Finally I used putNextEntry(…) and write(…) methods to compress and write the contents to the zip file. Closing the streams in a good practice and I followed that J
Make changes and play around the code.Java Code:FileOutputStream fos = new FileOutputStream ( "C:\a.zip" ); ZipOutputStream zip = new ZipOutputStream ( fos ); zip.setLevel( 9 ); zip.setMethod( ZipOutputStream.DEFLATED ); File elementFile = new File ("C:\arraylist.data"); ZipEntry entry = new ZipEntry( "C:\arraylist.data" ); int fileLength = (int)elementFile.length(); FileInputStream fis = new FileInputStream ( elementFile ); byte wholeFile = new byte [fileLength]; int bytesRead = fis.read( wholeFile , 0 , fileLength ); fis.close(); zip.putNextEntry( entry ); zip.write( wholeFile , 0, fileLength ); zip.closeEntry(); zip.close();