How to Zip a file using Java? - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

How to Zip a file using Java?

Share This

The following Code Snippet compresses a file and zips it to a target zip file. The name of the class is SimpleZipper and it takes the absolute path of the file to be zipped and the target zipped file as input. The class is tested with the main method inside the class body itself.

This class utilizes java.util.zip and the code is commented for easy understanding.

The flow of the code is like
  • Create file output stream out of target file path
  • Create a zip output stream out of the file output stream
  • Extract the file name out of the input file (to be zipped) path
  • Extract the file name out of the input file (to be zipped) path
  • Create the zip entry out of the file name
  • Put the entry to the zip output stream
  • Create the file input stream out of the input file to be zipped
  • Finally, read the input file and write it to the zip output stream

Here goes the code
package com.t4b.util.zip.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class TestMain { private String srcPath; private String zipPath; public TestMain(String srcPath, String zipPath) { this.srcPath = srcPath; this.zipPath = zipPath; } public void zip() { try { byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(new File(zipPath)); ZipOutputStream zos = new ZipOutputStream(fos); String zipEntryString = srcPath.substring(srcPath.lastIndexOf("\\") + 1); ZipEntry zipEntry = new ZipEntry(zipEntryString); zos.putNextEntry(zipEntry); FileInputStream in = new FileInputStream(srcPath); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); zos.close(); System.out.println("Zipped file is ready at " + zipPath); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String args[]) { String file = "abc.txt"; String loc = "test.zip"; TestMain zipper = new TestMain(file, loc); zipper.zip(); } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.