Java: PKZip Compression

From Wiki

Compressing a file using PKZip format

Código / Code

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

public class PKZIPCompress {
    public static void main(String[] args) {
        try {
            // The name of the file to be compressed
            String fileName = "example.txt";
            
            FileInputStream fis = new FileInputStream(fileName); // Create a file input stream            
            FileOutputStream fos = new FileOutputStream("example.zip"); // Create a file output stream
            
            ZipOutputStream zos = new ZipOutputStream(fos); // Create a ZipOutputStream
            ZipEntry zipEntry = new ZipEntry(fileName); // Create a new zip entry
            
            zos.putNextEntry(zipEntry);  // Put the zip entry into the ZipOutputStream
            
            byte[] buffer = new byte[1024]; // Create a buffer for reading the files
            
            // Read the file and write it to the ZipOutputStream
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            
            fis.close(); // Close the input stream
            zos.closeEntry(); // Close the zip entry
            zos.close(); // Close the ZipOutputStream
            
            System.out.println(fileName + " was successfully compressed to example.zip");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Ver também