The package java.util.zip provides support to compress and decompress files in Zip and Gzip formats.
Here's an example to compress a zip file:
try( // Open input stream FileInputStream fis = new FileInputStream("C:/test.txt"); // Open output stream FileOutputStream fos = new FileOutputStream("C:/test.zip"); ZipOutputStream zos = new ZipOutputStream(fos); ) { zos.putNextEntry(new ZipEntry("test.txt")); byte[] b = new byte[1024]; int count = 0; // Compress file while ((count = fis.read(b)) > 0) { System.out.println(); zos.write(b, 0, count); } }
Here's an example to decompress the same zip file:
try( // Open input stream FileInputStream fis = new FileInputStream("C:/test.zip"); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zis = new ZipInputStream(bis); // Open output stream FileOutputStream fos = new FileOutputStream("C:/test.txt"); ) { // Find file to decompress ZipEntry ze = null; while ((ze = zis.getNextEntry()) != null) { if (ze.getName().equals("test.txt")) { // Decompress file byte[] buffer = new byte[8192]; int len = 0; while ((len = zis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.