Creating ZIP files

21 December 2007

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

 
	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();

Make changes and play around the code.

del.icio.us:Creating ZIP files  digg:Creating ZIP files  spurl:Creating ZIP files  wists:Creating ZIP files  simpy:Creating ZIP files  newsvine:Creating ZIP files  blinklist:Creating ZIP files  furl:Creating ZIP files  reddit:Creating ZIP files  fark:Creating ZIP files  blogmarks:Creating ZIP files  Y!:Creating ZIP files  smarking:Creating ZIP files  magnolia:Creating ZIP files  segnalo:Creating ZIP files  gifttagging:Creating ZIP files

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Creating ZIP files

Leave a Reply