Share on Google+Share on Google+

Java file zip

In this section, you will learn how to create a zip file.

Java file zip

In this section, you will learn how to create a zip file.

The ZIP file format is used for the distribution and storage of files. It is a compressed format file which takes less space then the original file. The zip file can store large number of file. If needed, user can extract the files from the zip file.

Now to create a zip file, we have used the package You can see in the given example, we have used ZipOutputStream which implements an output stream filter for writing files in the ZIP file format. Then we have used ZipEntry to represent a ZIP file entry.

setLevel(): This method of ZipOutputStream class sets the compression level for subsequent entries.

putNextEntry(): This method of ZipOutputStream class starts writing a new ZIP file entry and positions the stream to the start of the entry data.

write(): This method of ZipOutputStream class writes an array of bytes to the current ZIP entry data.

finish(): This method of ZipOutputStream class finishes writing the contents of the ZIP output stream without closing the underlying stream.

close(): This method of ZipOutputStream class closes the ZIP output stream as well as the stream being filtered.

Here is the code:


class FileZip {
	public static void main(String[] args) throws Exception {
		String filename = "C:/file.txt";
		byte[] b = new byte[1024];
		FileInputStream fis = new FileInputStream(filename);, 0, b.length);
		ZipOutputStream zos = new ZipOutputStream(
				(OutputStream) new FileOutputStream("C:/"));
		ZipEntry entry = new ZipEntry(filename);
		entry.setSize((long) b.length);
		zos.write(b, 0, b.length);

By using the above code, you can create a zip file of any file or a list of files.



Posted on: September 22, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null