To compress a document and save it as a ZIP file in Java, you can use the java.util.zip
package. Here's a step-by-step example:
Steps:
- Create a
ZipOutputStream
to write compressed data. - Use a
FileOutputStream
to create the output ZIP file. - Add files to the ZIP using
ZipEntry
and write the file's content to theZipOutputStream
.
Example Code:
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 ZipFileExample { public static void main(String[] args) { // Path of the file to be compressed String filePath = "path/to/your/document.txt"; // Path of the output ZIP file String zipFilePath = "path/to/your/compressed_document.zip"; try { zipFile(filePath, zipFilePath); System.out.println("File compressed successfully!"); } catch (IOException e) { System.err.println("Error while compressing file: " + e.getMessage()); } } public static void zipFile(String filePath, String zipFilePath) throws IOException { File fileToZip = new File(filePath); if (!fileToZip.exists()) { throw new IOException("File not found: " + filePath); } try ( FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zipOut = new ZipOutputStream(fos); FileInputStream fis = new FileInputStream(fileToZip) ) { // Create a new ZIP entry ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); // Write file data to ZIP output stream byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { zipOut.write(buffer, 0, bytesRead); } // Close the current ZIP entry zipOut.closeEntry(); } } }
Explanation:
- Input File: Replace
path/to/your/document.txt
with the file path of the document you want to compress. - Output ZIP: Replace
path/to/your/compressed_document.zip
with the desired ZIP file's path. - Buffering: A buffer of size 1024 bytes is used to read and write data in chunks for efficiency.
Output:
The document will be compressed and saved as a .zip
file, reducing memory usage.
Let me know if you need further clarification