Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Thursday, February 13, 2020

Files Compressing and Decompressing in Java (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.

No comments:

Post a Comment

Please do not add any spam links in the comments section.