How to Compress a File in ZIP Format in Java


In this example we will show the method to compress a file in ZIP format in Java.

Source Code

package com.beginner.examples;

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

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

		File file = new File("example.txt");
		File zipFile = new File("example.zip");
		FileInputStream fis = new FileInputStream(file);
        ZipEntry entry = new ZipEntry(file.getName());
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
        zos.putNextEntry(entry);

        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = fis.read(buf)) != -1) 
        {
            zos.write(buf, 0, len);
        }
        zos.flush();
        fis.close();
        zos.closeEntry();
        System.out.println("Done!");
    }
}

Output:

Done!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments