$show=/label

Files Compressing and Decompressing in Java (Zipping and Unzipping)

SHARE:

A quick guide to compress and decompress the files in java using java built-in api methods in java.util.zip package. Example programs to files zipping and unzipping.

1. Introduction


In this tutorial, We will be learning how to compress a file in java and how to decompress the same compressed file using java java.util.zip package.

Java is built with zipping(archiving) files utilities in java.util.zip which you can find all the zipping and unzipping related utilities.

In this article, we will see how to compress a file, multiple files, and files in folder or directory. At last, we will how to unzip an archived file. All the examples shown are can be done in java 8 or higher versions.

Files Compressing and Decompressing in Java (Zipping and Unzipping)




2. Zipping a single file


Let us see a simple example program on how to zip or compress or archive a file in java using ZipEntry and ZipOutputStream classes. This calss takes input "src-file.txt" and generates a compressed file "compressed.zip" file.

package com.java.w3schools.blog.java.program.to.files;

/**
 * 
 * Java Program to compress a file.
 * 
 */
 
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 ZippingAFileExample {

 public static void main(String[] args) throws IOException {

  // src file
  String sourceFile = "src-file.txt";

  // compressed file name
  FileOutputStream fos = new FileOutputStream("compressed.zip");

  System.out.println("File compression started.");
  // output zip file stream.
  ZipOutputStream zipOut = new ZipOutputStream(fos);
  File fileToZip = new File(sourceFile);
  FileInputStream fis = new FileInputStream(fileToZip);

  // Creating zip file name.
  ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
  zipOut.putNextEntry(zipEntry);

  byte[] bytes = new byte[1024];
  int length;

  // writing content into zip or archieve file.
  while ((length = fis.read(bytes)) >= 0) {
   zipOut.write(bytes, 0, length);
  }
  zipOut.close();
  fis.close();
  fos.close();
  System.out.println("Done");
 }

}

3. Zipping Multiple Files in Single Program


In the above program, we have seen only one file compressing technique. But now, let us see the example program to compress a set of files. The below program converts "file-1.txt", "file-2.txt", "file-3.txt" three files into multifilesCompressed.zip file.

package com.java.w3schools.blog.java.program.to.files;

/**
 * 
 * Java Program to compress a multiple files at a time.
 * 
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZippingAFileExample {

 public static void main(String[] args) throws IOException {

  // storing the multiple files in arraylist
  List<String> srcFiles = Arrays.asList("file-1.txt", "file-2.txt", "file-3.txt");

  // output zipped file
  FileOutputStream fos = new FileOutputStream("multifilesCompressed.zip");

  System.out.println("Zipping started.");
  ZipOutputStream zipOut = new ZipOutputStream(fos);
  for (String srcFile : srcFiles) {

   File fileToZip = new File(srcFile);
   FileInputStream fis = new FileInputStream(fileToZip);
   // Creating a zip entry.
   ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
   zipOut.putNextEntry(zipEntry);

   byte[] bytes = new byte[1024];
   int length;
   while ((length = fis.read(bytes)) >= 0) {
    zipOut.write(bytes, 0, length);
   }
   fis.close();
  }
  zipOut.close();
  fos.close();
  System.out.println("Done");
 }

}

4. Zipping A Directory or Folder


Now, let us see how to zip an entire directory using a recursive approach with method a zipFile(). This program converts all have files from the "src" folder into a "DirSrcCompressed.zip" file.


package com.java.w3schools.blog.java.program.to.files;

/**
 * 
 * Java Program to compress a directory at a time.
 * 
 */
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 ZippingADirectory {

 public static void main(String[] args) throws IOException {
  String sourceFile = "src";
  FileOutputStream fos = new FileOutputStream("DirSrcCompressed.zip");
  ZipOutputStream zipOut = new ZipOutputStream(fos);
  File fileToZip = new File(sourceFile);

  zipFile(fileToZip, fileToZip.getName(), zipOut);
  zipOut.close();
  fos.close();
 }

 private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
  if (fileToZip.isHidden()) {
   return;
  }
  if (fileToZip.isDirectory()) {
   if (fileName.endsWith("/")) {
    zipOut.putNextEntry(new ZipEntry(fileName));
    zipOut.closeEntry();
   } else {
    zipOut.putNextEntry(new ZipEntry(fileName + "/"));
    zipOut.closeEntry();
   }
   File[] children = fileToZip.listFiles();
   for (File childFile : children) {
    zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
   }
   return;
  }
  FileInputStream fis = new FileInputStream(fileToZip);
  ZipEntry zipEntry = new ZipEntry(fileName);
  zipOut.putNextEntry(zipEntry);
  byte[] bytes = new byte[1024];
  int length;
  while ((length = fis.read(bytes)) >= 0) {
   zipOut.write(bytes, 0, length);
  }
  fis.close();
 }
}

Instread of zipping a complete folder, we can zip only .java or .docx or .xml files using listFiles(FilenameFilter filter).

How to traverse a folder in java recursively.

5. Unzipping a compressed file


Example program to unzip a compressed "multifilesCompressed.zip".

package com.java.w3schools.blog.java.program.to.files;

/**
 * 
 * Java Program to unzip a compressed .zip file.
 * 
 */
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.ZipInputStream;

public class UnzipFile {

 public static void main(String[] args) {
  String zipFilePath = "multifilesCompressed.zip";

  unzip(zipFilePath);
 }

 private static void unzip(String zipFilePath) {
  File dir = new File(".");
  // create output directory if it doesn't exist
  if (!dir.exists())
   dir.mkdirs();
  FileInputStream fis;
  // buffer for read and write data to file
  byte[] buffer = new byte[1024];
  try {
   fis = new FileInputStream(zipFilePath);
   ZipInputStream zis = new ZipInputStream(fis);
   ZipEntry ze = zis.getNextEntry();
   while (ze != null) {
    String fileName = ze.getName();
    File newFile = new File("." + File.separator + fileName);
    System.out.println("Unzipping to " + newFile.getAbsolutePath());
    // create directories for sub directories in zip
    new File(newFile.getParent()).mkdirs();
    FileOutputStream fos = new FileOutputStream(newFile);
    int len;
    while ((len = zis.read(buffer)) > 0) {
     fos.write(buffer, 0, len);
    }
    fos.close();
    // close this ZipEntry
    zis.closeEntry();
    ze = zis.getNextEntry();
   }
   // close last ZipEntry
   zis.closeEntry();
   zis.close();
   fis.close();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}

This program will be generated three files "file-1.txt", "file-2.txt", "file-3.txt".


6. Possible Exceptions


If the input file does not exists or file name is wrong then will get FileNotFoundException.

Exception in thread "main" java.io.FileNotFoundException: src-file.txt (No such file or directory)
 at java.base/java.io.FileInputStream.open0(Native Method)
 at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
 at java.base/java.io.FileInputStream.(FileInputStream.java:155)
 at com.java.w3schools.blog.java.program.to.files.ZippingAFileExample.main(ZippingAFileExample.java:18)


7. Conclusion


In this article, We have seen working examples of how to compress and decompress files, a set of files and directory.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,14,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,72,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,10,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Files Compressing and Decompressing in Java (Zipping and Unzipping)
Files Compressing and Decompressing in Java (Zipping and Unzipping)
A quick guide to compress and decompress the files in java using java built-in api methods in java.util.zip package. Example programs to files zipping and unzipping.
https://1.bp.blogspot.com/-vPwFP0xt3xo/XkWO73WbK0I/AAAAAAAACQ8/NFkfKCppoBsDYZlHVMBgcn0qN1b8qRGeACLcBGAsYHQ/s640/Files%2BCompressing%2Band%2BDecompressing%2Bin%2BJava%2B%2528Zipping%2Band%2BUnzipping%2529.png
https://1.bp.blogspot.com/-vPwFP0xt3xo/XkWO73WbK0I/AAAAAAAACQ8/NFkfKCppoBsDYZlHVMBgcn0qN1b8qRGeACLcBGAsYHQ/s72-c/Files%2BCompressing%2Band%2BDecompressing%2Bin%2BJava%2B%2528Zipping%2Band%2BUnzipping%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/02/java-files-compress-and-uncompress.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/02/java-files-compress-and-uncompress.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content