Java file zip


 

Java file zip

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

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 java..util.zip. 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:

import java.io.*;
import java.util.zip.*;

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);
		fis.read(b, 0, b.length);
		ZipOutputStream zos = new ZipOutputStream(
				(OutputStream) new FileOutputStream("C:/file.zip"));
		ZipEntry entry = new ZipEntry(filename);
		entry.setSize((long) b.length);
		zos.setLevel(6);
		zos.putNextEntry(entry);
		zos.write(b, 0, b.length);
		zos.finish();
		zos.close();
	}
}

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

Ads