To compress a document and save it as a ZIP file in Java

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:

  1. Create a ZipOutputStream to write compressed data.
  2. Use a FileOutputStream to create the output ZIP file.
  3. Add files to the ZIP using ZipEntry and write the file's content to the ZipOutputStream.

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:

  1. Input File: Replace path/to/your/document.txt with the file path of the document you want to compress.
  2. Output ZIP: Replace path/to/your/compressed_document.zip with the desired ZIP file's path.
  3. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值