zip

Create zip file from single file with ZipOutputStream

This is an example of how to create a zip file from a single File with ZipOutputStream. The ZipOutputStream class implements an output stream filter for writing files in the ZIP file format. Creating a zip file from a single File with ZipOutputStream implies that you should:

  • Create a FileOutputStream to write to the file with the specified name, that is the zipFile.
  • Create a new ZipOutputStream from the FileOutputStream, that is an output stream filter for writing files in the ZIP file format.
  • Create a new File instance by the given pathname of the file.
  • Create a FileInputStream by opening a connection to the file, in order to read the file.
  • Create a new ZipEntry with the name of the File and begin writing it to the ZipOutputStream. The default compression method will be used if no compression method was specified for the entry.
  • Read up to 1024 bytes of data from the file into an array of bytes, using the read(byte[] b) API method of FileInputStream and write the data to the current ZipEntry , using write(byte[] b, int off, int len) method of ZipOutputStream.
  • Close the ZipEntry, the ZipOutputStream and the FileInputStream, using their closeEntry() and close() API methods.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

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 CreateZipFileFromSingleFileWithZipOutputStream {
	
	public static void main(String[] args) {
		
		String zipFile = "C:/archive.zip";
		String srcFilename = "C:/srcfile.txt";
		
		try {
			
			// create byte buffer
			byte[] buffer = new byte[1024];

			FileOutputStream fos = new FileOutputStream(zipFile);

			ZipOutputStream zos = new ZipOutputStream(fos);
			
			File srcFile = new File(srcFilename);

			FileInputStream fis = new FileInputStream(srcFile);

			// begin writing a new ZIP entry, positions the stream to the start of the entry data
			zos.putNextEntry(new ZipEntry(srcFile.getName()));
			
			int length;

			while ((length = fis.read(buffer)) > 0) {
				zos.write(buffer, 0, length);
			}

			zos.closeEntry();

			// close the InputStream
			fis.close();

			// close the ZipOutputStream
			zos.close();
			
		}
		catch (IOException ioe) {
			System.out.println("Error creating zip file" + ioe);
		}
		
	}

}

 
This was an example of how to create a zip file from a single File with ZipOutputStream in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button