Search

Suggested keywords:
  • Java
  • Docker
  • Git
  • React
  • NextJs
  • Spring boot
  • Laravel

File Compression and Decompression in Java

  • Share this:

post-title

File compression and decompression are common tasks in software development, especially when dealing with large files or when transferring files over the network. Java provides built-in support for file compression and decompression using libraries such as java.util.zip. In this article, we'll explore how to compress and decompress files in Java with a simple example.

File Compression with java.util.zip

The java.util.zip package provides classes for reading and writing ZIP and GZIP files. For compression, we'll use ZipOutputStream, while for decompression, we'll use ZipInputStream. To compress and decompress using GZIP use GZIPOutputStream and GZIPInputStream

 

Step 1: Create a Method for File Compression

Let's create a method compressFile that takes the path of the file to be compressed and the path where the compressed file will be saved.

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileCompressionExample {

   public static void compressFile(String sourceFile, String zipFile) {
       try (FileOutputStream fos = new FileOutputStream(zipFile);
	            ZipOutputStream zos = new ZipOutputStream(fos);
	            FileInputStream fis = new FileInputStream(sourceFile)) {

           ZipEntry zipEntry = new ZipEntry(new File(sourceFile).getName());
           zos.putNextEntry(zipEntry);

           byte[] buffer = new byte[1024];
           int bytesRead;
           while ((bytesRead = fis.read(buffer)) != -1) {
               zos.write(buffer, 0, bytesRead);
           }

           zos.closeEntry();
           System.out.println("File compressed successfully.");

       } catch (IOException e) {
           e.printStackTrace();
       }
   }

   public static void main(String[] args) {
       String sourceFile = "path/to/source/file.txt";
       String zipFile = "path/to/compressed/file.zip";
       compressFile(sourceFile, zipFile);
   }
}

 

Explanation

1. compressFile method takes the path of the source file (sourceFile) and the path where the compressed file will be saved (zipFile).

2. It creates a FileOutputStream and a ZipOutputStream to write data to the ZIP file.

3. ZipEntry represents a single entry in a ZIP file. Here, we create a ZipEntry for the source file.

4. Read the source file in chunks (buffered reads) and writes them to the ZipOutputStream.

5. Close the ZipEntry, which marks the close of the current file.

6. Repeat steps from 3 to 5 to add more files to the current zip file

7. Close the output stream.

 

Step 2: Decompressing the ZIP File

Let's create a method decompressFile to decompress the ZIP file created in the previous step.

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileCompressionExample {

   public static void decompressFile(String zipFile, String outputFolder) {
       try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {

           ZipEntry zipEntry = zis.getNextEntry();
           while (zipEntry != null) {
               String fileName = zipEntry.getName();
               File newFile = new File(outputFolder + File.separator + fileName);

               new File(newFile.getParent()).mkdirs();

               FileOutputStream fos = new FileOutputStream(newFile);
               byte[] buffer = new byte[1024];
               int bytesRead;
               while ((bytesRead = zis.read(buffer)) != -1) {
                   fos.write(buffer, 0, bytesRead);
               }
               fos.close();
               zipEntry = zis.getNextEntry();
           }

           System.out.println("File decompressed successfully.");

       } catch (IOException e) {
           e.printStackTrace();
       }
   }

   public static void main(String[] args) {
       String zipFile = "path/to/compressed/file.zip";
       String outputFolder = "path/to/output/folder";
       decompressFile(zipFile, outputFolder);
   }
}

Explanation

1. decompressFile method takes the path of the ZIP file (zipFile) and the path of the output folder (outputFolder) where the decompressed files will be saved.

2. Create a ZipInputStream to read the contents of the ZIP file.

3. For each entry (file) in the ZIP file, create a corresponding file in the output folder and write the decompressed data into it.

4. Close the file output stream and look for another file entry in the ZIP file.

5. Repeat step 3 and 4 until all files are decompressed.

 

Conclusion

In this article, we've demonstrated how to compress and decompress files in Java using the java.util.zip package. File compression reduces file size for efficient storage and transmission, while decompression retrieves the original files. These techniques are essential for handling large amounts of data and are commonly used in various applications. The provided examples offer a simple yet effective way to implement file compression and decompression functionality in Java applications.

 

Muthu Annamalai

About author
Technical Writer | Pre-Final Year Student | Code & Community | Developer who works everyday to improve himself.