### Getting an InputStream for a Zip Entry Source: https://context7.com/srikanth-lingala/zip4j/llms.txt This section demonstrates how to get an InputStream for a specific zip entry's contents without extracting it to disk. This is useful for in-memory processing or streaming. ```APIDOC ## Getting an InputStream for a Zip Entry ### Description Get an input stream for reading a specific entry's contents directly without extracting to disk. Useful for processing zip contents in memory or streaming to other destinations. ### Method This is a Java code example demonstrating the usage of the Zip4j library. ### Endpoint N/A (This is a library usage example, not a web API endpoint.) ### Parameters N/A ### Request Example ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.io.inputstream.ZipInputStream; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.exception.ZipException; import java.io.IOException; import java.io.InputStream; public class ReadZipEntryStream { public static void main(String[] args) { try (ZipFile zipFile = new ZipFile("archive.zip")) { FileHeader fileHeader = zipFile.getFileHeader("data/config.json"); if (fileHeader != null) { try (InputStream inputStream = zipFile.getInputStream(fileHeader)) { // Read content into memory byte[] buffer = new byte[4096]; StringBuilder content = new StringBuilder(); int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { content.append(new String(buffer, 0, bytesRead)); } System.out.println("File content:\n" + content.toString()); } } } catch (ZipException | IOException e) { System.err.println("Error: " + e.getMessage()); } } } ``` ### Response N/A (This is a code execution example, not an API response.) ``` -------------------------------- ### List Files in Zip Archive (Zip4j) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Provides an example of how to list all files and entries within a zip archive using Zip4j. It retrieves a list of FileHeader objects, each containing information about an entry, and prints the file name of each entry. ```java List fileHeaders = new ZipFile("zipfile.zip").getFileHeaders(); fileHeaders.stream().forEach(fileHeader -> System.out.println(fileHeader.getFileName())); ``` -------------------------------- ### Monitor Zip4j Operations with ProgressMonitor Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md This example demonstrates how to enable background threading for a ZipFile operation and monitor its progress using the ProgressMonitor class. It includes a polling loop to check the state and percentage completion until the task reaches the READY state. ```java ZipFile zipFile = new ZipFile(generatedZipFile, PASSWORD); ProgressMonitor progressMonitor = zipFile.getProgressMonitor(); zipFile.setRunInThread(true); zipFile.addFolder(new File("/some/folder")); while (!progressMonitor.getState().equals(ProgressMonitor.State.READY)) { System.out.println("Percentage done: " + progressMonitor.getPercentDone()); System.out.println("Current file: " + progressMonitor.getFileName()); System.out.println("Current task: " + progressMonitor.getCurrentTask()); Thread.sleep(100); } if (progressMonitor.getResult().equals(ProgressMonitor.Result.SUCCESS)) { System.out.println("Successfully added folder to zip"); } else if (progressMonitor.getResult().equals(ProgressMonitor.Result.ERROR)) { System.out.println("Error occurred. Error message: " + progressMonitor.getException().getMessage()); } else if (progressMonitor.getResult().equals(ProgressMonitor.Result.CANCELLED)) { System.out.println("Task cancelled"); } ``` -------------------------------- ### Add a Folder to a Zip Archive Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Illustrates how to recursively add a directory to a zip file. Includes examples of using ZipParameters to customize behavior, such as excluding the root folder or filtering specific file types. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.exception.ZipException; import java.io.File; public class AddFolderToZip { public static void main(String[] args) { try { new ZipFile("project-backup.zip").addFolder(new File("/path/to/project")); ZipParameters params = new ZipParameters(); params.setIncludeRootFolder(false); new ZipFile("contents-only.zip").addFolder(new File("/path/to/project"), params); ZipParameters filterParams = new ZipParameters(); filterParams.setExcludeFileFilter(file -> file.getName().endsWith(".log") || file.getName().startsWith(".") ); new ZipFile("filtered-backup.zip").addFolder(new File("/path/to/project"), filterParams); System.out.println("Folder added to zip successfully"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### Get InputStream for Zip Entry (Java) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Obtains an InputStream for a specific entry within a zip file. This allows reading the content of the entry directly. The entry name can be relative to its directory. ```java ZipFile zipFile = new ZipFile("filename.zip"); FileHeader fileHeader = zipFile.getFileHeader("entry_name_in_zip.txt"); InputStream inputStream = zipFile.getInputStream(fileHeader); ``` -------------------------------- ### Manage Zip Comments with Zip4j Source: https://context7.com/srikanth-lingala/zip4j/llms.txt This Java example illustrates how to set, retrieve, and remove comments from a zip archive using the Zip4j library. Zip comments are useful for storing metadata or descriptive notes directly within the archive. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; public class ZipCommentExample { public static void main(String[] args) { try { ZipFile zipFile = new ZipFile("archive.zip"); // Set a comment zipFile.setComment("Backup created on 2024-01-15. Contains project files v2.0"); System.out.println("Comment set successfully"); // Read the comment String comment = zipFile.getComment(); System.out.println("Archive comment: " + comment); // Remove comment by setting empty string zipFile.setComment(""); System.out.println("Comment removed"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### Create a Zip File with a Single File Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Demonstrates how to initialize a ZipFile object and add a single file to an archive using either a string path or a File object. This process uses default DEFLATE compression settings. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; public class CreateSingleFileZip { public static void main(String[] args) { try { new ZipFile("output.zip").addFile("document.txt"); new ZipFile("output.zip").addFile(new java.io.File("document.txt")); System.out.println("Zip file created successfully"); } catch (ZipException e) { System.err.println("Error creating zip: " + e.getMessage()); } } } ``` -------------------------------- ### Set, Remove, and Get Zip File Comment Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md APIs for managing the comment associated with a zip archive. ```APIDOC ## Manage Zip File Comment ### Description This section describes how to set, remove, and retrieve the comment associated with a zip archive. ### Set Zip File Comment #### Description Sets or updates the comment for a zip archive. #### Method `setComment(String comment)` #### Endpoint N/A (Library method) #### Request Example ```java new ZipFile("some_zip_file.zip").setComment("This is a sample comment."); ``` ### Remove Zip File Comment #### Description Removes the comment from a zip archive by setting it to an empty string. #### Method `setComment(String comment)` #### Endpoint N/A (Library method) #### Request Example ```java new ZipFile("some_zip_file.zip").setComment(""); ``` ### Get Zip File Comment #### Description Retrieves the comment associated with a zip archive. #### Method `getComment()` #### Endpoint N/A (Library method) #### Request Example ```java String comment = new ZipFile("some_zip_file.zip").getComment(); ``` #### Response - **comment** (String) - The comment of the zip file, or an empty string if no comment is set. ``` -------------------------------- ### Create Zip with Folder / Add Folder to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Illustrates how to add an entire folder, including its contents, to a zip archive. It also shows how to exclude specific files during the folder addition process using an ExcludeFileFilter, available since v2.6. ```java new ZipFile("filename.zip").addFolder(new File("/users/some_user/folder_to_add")); ``` ```java ExcludeFileFilter excludeFileFilter = filesToExclude::contains; ZipParameters zipParameters = new ZipParameters(); zipParameters.setExcludeFileFilter(excludeFileFilter); new ZipFile("filename.zip").addFolder(new File("/users/some_user/folder_to_add"), zipParameters); ``` -------------------------------- ### Get Zip File Comment (Zip4j) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates how to retrieve the comment associated with a zip file using Zip4j's getComment() method. ```java new ZipFile("some_zip_file.zip").getComment(); ``` -------------------------------- ### Create Zip with Multiple Files / Add Multiple Files to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Shows how to create a zip file containing multiple files or add multiple files to an existing zip archive. This method takes a list of File objects. ```java new ZipFile("filename.zip").addFiles(Arrays.asList(new File("first_file"), new File("second_file"))); ``` -------------------------------- ### Managing Zip Comments Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Set, get, or remove comments from a zip archive. Comments can be used to store metadata or notes about the archive contents. ```APIDOC ## Managing Zip Comments Set, get, or remove comments from a zip archive. Comments can be used to store metadata or notes about the archive contents. ### Method Not applicable (Java example) ### Endpoint Not applicable (Java example) ### Parameters Not applicable (Java example) ### Request Example ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; public class ZipCommentExample { public static void main(String[] args) { try { ZipFile zipFile = new ZipFile("archive.zip"); // Set a comment zipFile.setComment("Backup created on 2024-01-15. Contains project files v2.0"); System.out.println("Comment set successfully"); // Read the comment String comment = zipFile.getComment(); System.out.println("Archive comment: " + comment); // Remove comment by setting empty string zipFile.setComment(""); System.out.println("Comment removed"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` ### Response Not applicable (Java example) ``` -------------------------------- ### Create a Zip File with Multiple Files Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Shows how to efficiently add a list of files to a zip archive in a single operation, which reduces I/O overhead compared to individual additions. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; import java.io.File; import java.util.Arrays; import java.util.List; public class CreateMultiFileZip { public static void main(String[] args) { try { List filesToAdd = Arrays.asList( new File("report.pdf"), new File("data.csv"), new File("image.png") ); new ZipFile("archive.zip").addFiles(filesToAdd); System.out.println("Multiple files added to zip successfully"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### Add Multiple Files to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Shows how to add multiple files to a zip archive simultaneously. ```APIDOC ## Add Multiple Files to Zip ### Description Adds multiple files to a zip archive. This is useful for batch operations. ### Method `ZipFile.addFiles()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java List filesToAdd = Arrays.asList(new File("first_file"), new File("second_file")); new ZipFile("filename.zip").addFiles(filesToAdd); ``` ### Response #### Success Response (200) N/A (Library method, no explicit HTTP response) #### Response Example N/A ``` -------------------------------- ### Create Split Zip File Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Illustrates how to create a zip file that is split into multiple smaller files once a specified size limit is reached. This includes setting the split size and optionally applying password protection and AES encryption. ```java List filesToAdd = Arrays.asList( new File("somefile"), new File("someotherfile") ); ZipFile zipFile = new ZipFile("filename.zip"); zipFile.createSplitZipFile(filesToAdd, new ZipParameters(), true, 10485760); // using 10MB in this example ``` ```java ZipParameters zipParameters = new ZipParameters(); zipParameters.setEncryptFiles(true); zipParameters.setEncryptionMethod(EncryptionMethod.AES); List filesToAdd = Arrays.asList( new File("somefile"), new File("someotherfile") ); ZipFile zipFile = new ZipFile("filename.zip", "password".toCharArray()); zipFile.createSplitZipFile(filesToAdd, zipParameters, true, 10485760); // using 10MB in this example ``` -------------------------------- ### Create Zip with STORE Compression / Add to STORE Compression Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Explains how to create a zip file using the 'STORE' compression method, which means no compression is applied. This can be achieved by setting ZipParameters. This method can be applied to all other addition methods. ```java ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(CompressionMethod.STORE); new ZipFile("filename.zip").addFile("fileToAdd", zipParameters); ``` -------------------------------- ### Add Files to Zip Archive with ZipOutputStream (Java) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates how to add multiple files to a zip archive using ZipOutputStream. It supports various compression methods, encryption, and specifies parameters like file name and compression method. ```java import net.lingala.zip4j.io.outputstream.ZipOutputStream; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.model.enums.AesKeyStrength; import net.lingala.zip4j.model.enums.CompressionMethod; import net.lingala.zip4j.model.enums.EncryptionMethod; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; public class ZipOutputStreamExample { public void zipOutputStreamExample(File outputZipFile, List filesToAdd, char[] password, CompressionMethod compressionMethod, boolean encrypt, EncryptionMethod encryptionMethod, AesKeyStrength aesKeyStrength) throws IOException { ZipParameters zipParameters = buildZipParameters(compressionMethod, encrypt, encryptionMethod, aesKeyStrength); byte[] buff = new byte[4096]; int readLen; try(ZipOutputStream zos = initializeZipOutputStream(outputZipFile, encrypt, password)) { for (File fileToAdd : filesToAdd) { // Entry size has to be set if you want to add entries of STORE compression method (no compression) // This is not required for deflate compression if (zipParameters.getCompressionMethod() == CompressionMethod.STORE) { zipParameters.setEntrySize(fileToAdd.length()); } zipParameters.setFileNameInZip(fileToAdd.getName()); zos.putNextEntry(zipParameters); try(InputStream inputStream = new FileInputStream(fileToAdd)) { while ((readLen = inputStream.read(buff)) != -1) { zos.write(buff, 0, readLen); } } zos.closeEntry(); } } } private ZipOutputStream initializeZipOutputStream(File outputZipFile, boolean encrypt, char[] password) throws IOException { FileOutputStream fos = new FileOutputStream(outputZipFile); if (encrypt) { return new ZipOutputStream(fos, password); } return new ZipOutputStream(fos); } private ZipParameters buildZipParameters(CompressionMethod compressionMethod, boolean encrypt, EncryptionMethod encryptionMethod, AesKeyStrength aesKeyStrength) { ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(compressionMethod); zipParameters.setEncryptionMethod(encryptionMethod); zipParameters.setAesKeyStrength(aesKeyStrength); zipParameters.setEncryptFiles(encrypt); return zipParameters; } } ``` -------------------------------- ### Extract Single File from Zip Archives with Zip4j Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Provides examples for extracting a specific file from a zip archive without extracting the entire content. It supports extracting by file name, renaming the extracted file, extracting entire directories, and using FileHeader for more control. This method also works with password-protected archives. Dependencies include the Zip4j library. ```Java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.exception.ZipException; public class ExtractSingleFile { public static void main(String[] args) { try { ZipFile zipFile = new ZipFile("archive.zip"); // Extract specific file by name zipFile.extractFile("documents/report.pdf", "/output/folder"); // Extract with a new name zipFile.extractFile("documents/report.pdf", "/output/folder", "renamed-report.pdf"); // Extract entire folder from zip zipFile.extractFile("images/", "/output/folder"); // Extract using FileHeader for more control FileHeader fileHeader = zipFile.getFileHeader("config.xml"); if (fileHeader != null) { zipFile.extractFile(fileHeader, "/output/folder"); } else { System.out.println("File not found in archive"); } // Extract from password-protected zip new ZipFile("secure.zip", "password".toCharArray()) .extractFile("secret.txt", "/output/folder"); System.out.println("File extracted successfully"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### Add Single File to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates how to add a single file to a new or existing zip archive. ```APIDOC ## Add Single File to Zip ### Description Adds a single file to a zip archive. If the zip file does not exist, it will be created. Otherwise, the file will be added to the existing archive. ### Method `ZipFile.addFile()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Using filename directly new ZipFile("filename.zip").addFile("filename.ext"); // Using File object new ZipFile("filename.zip").addFile(new File("filename.ext")); ``` ### Response #### Success Response (200) N/A (Library method, no explicit HTTP response) #### Response Example N/A ``` -------------------------------- ### Create Password Protected Zip (AES) / Add Files to Password Protected Zip (AES) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Shows how to create a password-protected zip file using AES encryption. It includes setting encryption method, key strength, and applying it when adding multiple files. A password is provided as a char array. ```java ZipParameters zipParameters = new ZipParameters(); zipParameters.setEncryptFiles(true); zipParameters.setEncryptionMethod(EncryptionMethod.AES); // Below line is optional. AES 256 is used by default. You can override it to use AES 128. AES 192 is supported only for extracting. zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256); List filesToAdd = Arrays.asList( new File("somefile"), new File("someotherfile") ); ZipFile zipFile = new ZipFile("filename.zip", "password".toCharArray()); zipFile.addFiles(filesToAdd, zipParameters); ``` -------------------------------- ### Add Folder to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Explains how to add an entire folder, including its contents, to a zip archive. ```APIDOC ## Add Folder to Zip ### Description Adds a folder and all its contents recursively to a zip archive. ### Method `ZipFile.addFolder()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Basic folder addition new ZipFile("filename.zip").addFolder(new File("/users/some_user/folder_to_add")); // Folder addition with exclusion filter (since v2.6) ExcludeFileFilter excludeFileFilter = filesToExclude::contains; ZipParameters zipParameters = new ZipParameters(); zipParameters.setExcludeFileFilter(excludeFileFilter); new ZipFile("filename.zip").addFolder(new File("/users/some_user/folder_to_add"), zipParameters); ``` ### Response #### Success Response (200) N/A (Library method, no explicit HTTP response) #### Response Example N/A ``` -------------------------------- ### POST /addFolder Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Adds an entire directory and its contents recursively to a zip archive with optional filtering. ```APIDOC ## POST /addFolder ### Description Adds a directory to the zip archive, preserving the internal structure. ### Method POST ### Parameters #### Request Body - **folderPath** (File) - Required - The directory to add. - **parameters** (ZipParameters) - Optional - Configuration for root folder inclusion or file filters. ### Request Example ZipParameters params = new ZipParameters(); params.setIncludeRootFolder(false); new ZipFile("backup.zip").addFolder(new File("/path/to/dir"), params); ### Response #### Success Response (200) - **status** (String) - Folder added to zip successfully. ``` -------------------------------- ### Configure Charset and Buffer Size in Zip4j Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Shows how to customize character encoding for international file names and adjust the I/O buffer size to optimize performance for large file operations. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class ZipConfiguration { public static void main(String[] args) { try { ZipFile zipFile = new ZipFile("international-archive.zip"); zipFile.setCharset(StandardCharsets.UTF_8); zipFile.setBufferSize(64 * 1024); zipFile.setUseUtf8CharsetForPasswords(true); Charset currentCharset = zipFile.getCharset(); System.out.println("Current charset: " + currentCharset.name()); System.out.println("Buffer size: " + zipFile.getBufferSize() + " bytes"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### POST /zip/create Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Creates a ZIP archive by streaming files into it using ZipOutputStream. Supports compression methods and optional encryption. ```APIDOC ## POST /zip/create ### Description Adds multiple files to a new ZIP archive using a streaming approach. This is ideal for large files where memory efficiency is required. ### Method POST ### Endpoint /zip/create ### Parameters #### Request Body - **outputZipFile** (File) - Required - The destination file path for the ZIP archive. - **filesToAdd** (List) - Required - A list of files to be compressed. - **password** (char[]) - Optional - Password for encrypted archives. - **compressionMethod** (Enum) - Required - Compression type (e.g., STORE, DEFLATE). - **encrypt** (boolean) - Optional - Whether to enable file encryption. ### Request Example { "outputZipFile": "/path/to/archive.zip", "filesToAdd": ["/path/to/file1.txt"], "compressionMethod": "DEFLATE", "encrypt": false } ### Response #### Success Response (200) - **status** (string) - Indicates successful creation of the archive. #### Response Example { "status": "success" } ``` -------------------------------- ### Listing All Files in a Zip Source: https://context7.com/srikanth-lingala/zip4j/llms.txt This section explains how to retrieve metadata for all entries within a zip archive, including file names, sizes, compression details, and encryption status. ```APIDOC ## Listing All Files in a Zip ### Description Retrieve metadata about all entries in a zip archive including file names, sizes, compression methods, and encryption status. ### Method This is a Java code example demonstrating the usage of the Zip4j library. ### Endpoint N/A (This is a library usage example, not a web API endpoint.) ### Parameters N/A ### Request Example ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.exception.ZipException; import java.util.List; public class ListZipContents { public static void main(String[] args) { try { ZipFile zipFile = new ZipFile("archive.zip"); List fileHeaders = zipFile.getFileHeaders(); System.out.println("Contents of archive.zip:"); System.out.println("----------------------------------------"); for (FileHeader fileHeader : fileHeaders) { System.out.printf("Name: %s%n", fileHeader.getFileName()); System.out.printf(" Size: %d bytes (compressed: %d bytes)%n", fileHeader.getUncompressedSize(), fileHeader.getCompressedSize()); System.out.printf(" Encrypted: %s%n", fileHeader.isEncrypted()); System.out.printf(" Directory: %s%n", fileHeader.isDirectory()); System.out.printf(" CRC: %d%n", fileHeader.getCrc()); System.out.println(); } System.out.println("Total entries: " + fileHeaders.size()); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` ### Response N/A (This is a code execution example, not an API response.) ``` -------------------------------- ### Create Zip with Single File / Add Single File to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates how to create a new zip file containing a single file or add a single file to an existing zip archive using Zip4j. It supports adding files directly or via a File object. ```java new ZipFile("filename.zip").addFile("filename.ext"); ``` ```java new ZipFile("filename.zip").addFile(new File("filename.ext")); ``` -------------------------------- ### Create Zip Archives with ZipOutputStream Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Demonstrates how to use ZipOutputStream to write files into a zip archive. It supports optional AES encryption and adding empty folders to the archive. ```java import net.lingala.zip4j.io.outputstream.ZipOutputStream; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.model.enums.AesKeyStrength; import net.lingala.zip4j.model.enums.CompressionMethod; import net.lingala.zip4j.model.enums.EncryptionMethod; import java.io.*; import java.util.List; public class ZipOutputStreamExample { public void createZipWithStreams(File outputZipFile, List filesToAdd, char[] password, boolean encrypt) throws IOException { ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(CompressionMethod.DEFLATE); if (encrypt) { zipParameters.setEncryptFiles(true); zipParameters.setEncryptionMethod(EncryptionMethod.AES); zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256); } try (FileOutputStream fos = new FileOutputStream(outputZipFile); ZipOutputStream zos = encrypt ? new ZipOutputStream(fos, password) : new ZipOutputStream(fos)) { byte[] buffer = new byte[4096]; int readLen; for (File fileToAdd : filesToAdd) { zipParameters.setFileNameInZip(fileToAdd.getName()); zos.putNextEntry(zipParameters); try (FileInputStream fis = new FileInputStream(fileToAdd)) { while ((readLen = fis.read(buffer)) != -1) { zos.write(buffer, 0, readLen); } } zos.closeEntry(); } zos.setComment("Created with Zip4j ZipOutputStream"); } System.out.println("Zip created successfully with ZipOutputStream"); } public void addEmptyFolder(ZipOutputStream zos, String folderName) throws IOException { ZipParameters params = new ZipParameters(); params.setFileNameInZip(folderName.endsWith("/") ? folderName : folderName + "/"); zos.putNextEntry(params); zos.closeEntry(); } } ``` -------------------------------- ### Adding Stream Content to Zip Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Explains how to add content directly from an input stream to a zip archive, useful for generating files in memory or from dynamic sources. Supports encryption. ```APIDOC ## Adding Stream Content to Zip Add content directly from an input stream to a zip archive without needing a file on disk. Essential for streaming applications and in-memory content. ### Method This functionality is demonstrated using the `ZipFile` class from the `net.lingala.zip4j` library in Java. ### Endpoints While there isn't a direct HTTP endpoint, the operations are performed on a local zip file. ### Operations - **Add stream content**: Use `zipFile.addStream(inputStream, parameters)`. - **Specify file name**: Use `ZipParameters.setFileNameInZip(String fileName)`. - **Add encrypted stream**: Set `ZipParameters.setEncryptFiles(true)` and `ZipParameters.setEncryptionMethod(EncryptionMethod.AES)`. ### Request Example (Adding a simple text file from a string stream) ```java String content = "This content was added from a stream!"; InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); ZipParameters parameters = new ZipParameters(); parameters.setFileNameInZip("generated/content.txt"); zipFile.addStream(inputStream, parameters); ``` ### Request Example (Adding encrypted JSON from a stream) ```java ZipFile secureZip = new ZipFile("secure-stream.zip", "password".toCharArray()); ZipParameters encryptedParams = new ZipParameters(); encryptedParams.setFileNameInZip("secrets/data.json"); encryptedParams.setEncryptFiles(true); encryptedParams.setEncryptionMethod(EncryptionMethod.AES); String jsonData = "{\"key\": \"secret-value\"}"; InputStream jsonStream = new ByteArrayInputStream(jsonData.getBytes(StandardCharsets.UTF_8)); secureZip.addStream(jsonStream, encryptedParams); ``` ### Response - **Success Response (200)**: Stream content added to zip successfully. A confirmation message is typically printed to the console. ### Error Handling - **ZipException**: Catches errors during zip file operations. ``` -------------------------------- ### POST /addFiles Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Adds a collection of files to a zip archive in a single operation to optimize I/O performance. ```APIDOC ## POST /addFiles ### Description Adds a list of files to a zip archive efficiently. ### Method POST ### Parameters #### Request Body - **files** (List) - Required - A list of File objects to be compressed into the archive. ### Request Example List files = Arrays.asList(new File("file1.txt"), new File("file2.txt")); new ZipFile("archive.zip").addFiles(files); ### Response #### Success Response (200) - **status** (String) - Multiple files added to zip successfully. ``` -------------------------------- ### Extract Files from Zip Archive with ZipInputStream (Java) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Shows how to extract all files from a zip archive using ZipInputStream. It iterates through each entry, creates a corresponding file, and writes the entry's content to it. Supports password-protected archives. ```java import net.lingala.zip4j.io.inputstream.ZipInputStream; import net.lingala.zip4j.model.LocalFileHeader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class ZipInputStreamExample { public void extractWithZipInputStream(File zipFile, char[] password) throws IOException { LocalFileHeader localFileHeader; int readLen; byte[] readBuffer = new byte[4096]; InputStream inputStream = new FileInputStream(zipFile); try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, password)) { while ((localFileHeader = zipInputStream.getNextEntry()) != null) { File extractedFile = new File(localFileHeader.getFileName()); try (OutputStream outputStream = new FileOutputStream(extractedFile)) { while ((readLen = zipInputStream.read(readBuffer)) != -1) { outputStream.write(readBuffer, 0, readLen); } } } } } } ``` -------------------------------- ### Create Password Protected Zip (Zip Standard) / Add Files to Password Protected Zip (Zip Standard) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates creating a password-protected zip file using the traditional Zip Standard encryption method. This is an alternative to AES encryption and is configured by setting the encryption method in ZipParameters. ```java ZipParameters zipParameters = new ZipParameters(); zipParameters.setEncryptFiles(true); zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); List filesToAdd = Arrays.asList( new File("somefile"), new File("someotherfile") ); ZipFile zipFile = new ZipFile("filename.zip", "password".toCharArray()); zipFile.addFiles(filesToAdd, zipParameters); ``` -------------------------------- ### POST /addFile Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Adds a single file to a zip archive. If the archive does not exist, it is created automatically. ```APIDOC ## POST /addFile ### Description Adds a single file to a zip archive using the ZipFile instance. ### Method POST ### Parameters #### Request Body - **filePath** (String/File) - Required - The path or File object of the file to be added to the archive. ### Request Example new ZipFile("output.zip").addFile("document.txt"); ### Response #### Success Response (200) - **status** (String) - Zip file created or updated successfully. ``` -------------------------------- ### Create Zip from Stream / Add Stream to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates how to add data from an InputStream to a zip file. This method is useful for zipping data that is not yet stored in a file. Default zip parameters are used if none are specified. ```java new ZipFile("filename.zip").addStream(inputStream, new ZipParameters()); ``` -------------------------------- ### Add Stream to Zip Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Details how to add data from an input stream to a zip archive. ```APIDOC ## Add Stream to Zip ### Description Adds data from an input stream to a zip archive. This is useful for adding dynamically generated content. ### Method `ZipFile.addStream()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Using default zip parameters new ZipFile("filename.zip").addStream(inputStream, new ZipParameters()); ``` ### Response #### Success Response (200) N/A (Library method, no explicit HTTP response) #### Response Example N/A ``` -------------------------------- ### Create Zip Archive with STORE Compression (No Compression) using Zip4j Source: https://context7.com/srikanth-lingala/zip4j/llms.txt This Java code snippet illustrates how to create a zip archive without any compression using Zip4j's STORE method. This is beneficial for files that are already compressed or when speed of archiving is prioritized over file size reduction. It sets the compression method in ZipParameters. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.model.enums.CompressionMethod; import net.lingala.zip4j.exception.ZipException; public class CreateStoreZip { public static void main(String[] args) { try { ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(CompressionMethod.STORE); new ZipFile("stored-archive.zip").addFile("already-compressed.mp4", zipParameters); System.out.println("Store zip created (no compression)"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### Rename Entry in Zip File (Zip4j) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates how to rename a single entry within a zip file using Zip4j. This can be done by providing the file header and the new name, or by providing the old and new file names directly. It also explains how to handle entries within folders and how renaming a directory affects its contents. ```java ZipFile zipFile = new ZipFile("sample.zip"); FileHeader fileHeader = zipFile.getFileHeader("entry-to-be-changed.pdf"); zipFile.renameFile(fileHeader, "new-file-name.pdf"); ``` ```java new ZipFile("filename.zip").renameFile("entry-to-be-changed.pdf", "new-file-name.pdf"); ``` ```java new ZipFile("filename.zip").renameFile("some-folder/some-sub-folder/some-entry.pdf", "some-folder/some-sub-folder/new-entry.pdf"); ``` ```java new ZipFile("filename.zip").renameFile("some-folder/some-sub-folder/some-entry.pdf", "some-new-entry.pdf"); ``` ```java new ZipFile("filename.zip").renameFile("some-folder/some-sub-folder/some-entry.pdf", "folder-to-be-moved-to/sub-folder/new-entry.pdf"); ``` -------------------------------- ### Create Split Zip Archives with Zip4j Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Demonstrates how to create split zip archives that span multiple files with a specified maximum size per part. It covers both unencrypted and AES-encrypted split zip creation. Dependencies include the Zip4j library. Input is a list of files to add and the desired split length. ```Java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.model.enums.EncryptionMethod; import net.lingala.zip4j.exception.ZipException; import java.io.File; import java.util.Arrays; import java.util.List; public class CreateSplitZip { public static void main(String[] args) { try { List filesToAdd = Arrays.asList( new File("large-video.mp4"), new File("huge-database.sql") ); ZipFile zipFile = new ZipFile("large-archive.zip"); // Split at 100MB (minimum is 65536 bytes / 64KB) long splitLength = 100 * 1024 * 1024; // 100MB zipFile.createSplitZipFile(filesToAdd, new ZipParameters(), true, splitLength); // With encryption ZipParameters encryptedParams = new ZipParameters(); encryptedParams.setEncryptFiles(true); encryptedParams.setEncryptionMethod(EncryptionMethod.AES); ZipFile encryptedSplitZip = new ZipFile("encrypted-split.zip", "password".toCharArray()); encryptedSplitZip.createSplitZipFile(filesToAdd, encryptedParams, true, splitLength); System.out.println("Split zip files created: large-archive.z01, large-archive.z02, ..., large-archive.zip"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### Renaming and Moving Files in Zip Archives with Zip4j Source: https://context7.com/srikanth-lingala/zip4j/llms.txt Demonstrates how to rename individual files, move files into subdirectories, rename folders, and perform batch renaming operations within a zip archive using the ZipFile class. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.exception.ZipException; import java.util.HashMap; import java.util.Map; public class RenameInZip { public static void main(String[] args) { try { ZipFile zipFile = new ZipFile("archive.zip"); zipFile.renameFile("old-name.txt", "new-name.txt"); zipFile.renameFile("root-file.txt", "subfolder/moved-file.txt"); FileHeader fileHeader = zipFile.getFileHeader("document.pdf"); if (fileHeader != null) { zipFile.renameFile(fileHeader, "renamed-document.pdf"); } zipFile.renameFile("old-folder/", "new-folder/"); Map renameMap = new HashMap<>(); renameMap.put("file1.txt", "renamed1.txt"); renameMap.put("file2.txt", "archive/renamed2.txt"); renameMap.put("docs/readme.md", "docs/README.md"); zipFile.renameFiles(renameMap); System.out.println("Files renamed successfully"); } catch (ZipException e) { System.err.println("Error: " + e.getMessage()); } } } ``` -------------------------------- ### Rename Entries in Zip File Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Demonstrates three methods to rename entries within a zip file: using a FileHeader object, using the entry name directly, or using a map for multiple renames. ```APIDOC ## Rename Entries in Zip File ### Description This section details how to rename entries within a zip file using Zip4j. It covers renaming a single entry by its FileHeader, by its name, and renaming multiple entries simultaneously using a map. It also explains how to handle entries within folders and how renaming a directory affects its contents. ### Method 1: Using FileHeader #### Description Renames a zip entry by providing its `FileHeader` object and the new name. #### Code Example ```java ZipFile zipFile = new ZipFile("sample.zip"); FileHeader fileHeader = zipFile.getFileHeader("entry-to-be-changed.pdf"); zipFile.renameFile(fileHeader, "new-file-name.pdf"); ``` ### Method 2: Using Entry Name #### Description Renames a zip entry by providing its current name and the new name. #### Code Example ```java new ZipFile("filename.zip").renameFile("entry-to-be-changed.pdf", "new-file-name.pdf"); ``` ### Method 3: Using a Map for Multiple Renames #### Description Renames multiple zip entries at once by providing a map where keys are the current entry names and values are the new entry names. #### Code Example ```java Map fileNamesMap = new HashMap<>(); fileNamesMap.put("firstFile.txt", "newFileFirst.txt"); fileNamesMap.put("secondFile.pdf", "newSecondFile.pdf"); fileNamesMap.put("some-folder/thirdFile.bin", "some-folder/newThirdFile.bin"); new ZipFile("filename.zip").renameFiles(fileNamesMap); ``` ### Handling Entries in Folders #### Description When renaming entries within folders, the new file name must include the complete parent path. If the parent path is omitted, the entry will be moved to the root of the zip file. This also allows moving entries to different folders. #### Code Example (Renaming with full path) ```java new ZipFile("filename.zip").renameFile("some-folder/some-sub-folder/some-entry.pdf", "some-folder/some-sub-folder/new-entry.pdf"); ``` #### Code Example (Moving entry to root) ```java new ZipFile("filename.zip").renameFile("some-folder/some-sub-folder/some-entry.pdf", "some-new-entry.pdf"); ``` #### Code Example (Moving entry to a different folder) ```java new ZipFile("filename.zip").renameFile("some-folder/some-sub-folder/some-entry.pdf", "folder-to-be-moved-to/sub-folder/new-entry.pdf"); ``` ### Renaming Directories #### Description Renaming a directory entry will automatically update the paths of all entries within that directory to reflect the new directory name. ### Limitations #### Description Zip4j does not support renaming files in split zip archives and will throw an exception if attempted. ``` -------------------------------- ### Monitor Zip Operation Progress with Zip4j Source: https://context7.com/srikanth-lingala/zip4j/llms.txt This Java code demonstrates how to monitor the progress of zip operations using Zip4j's ProgressMonitor. It enables background thread execution for operations and provides real-time updates on the task's status, percentage completion, and current file being processed. It also shows how to handle the final result (success, error, or cancellation) and includes methods for cancelling, pausing, and resuming operations. ```java import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.progress.ProgressMonitor; import net.lingala.zip4j.exception.ZipException; import java.io.File; public class ProgressMonitorExample { public static void main(String[] args) { try { ZipFile zipFile = new ZipFile("large-archive.zip", "password".toCharArray()); ProgressMonitor progressMonitor = zipFile.getProgressMonitor(); // Enable background thread execution zipFile.setRunInThread(true); // Start the operation (returns immediately) zipFile.addFolder(new File("/large/folder/to/compress")); // Monitor progress while (!progressMonitor.getState().equals(ProgressMonitor.State.READY)) { System.out.printf("Progress: %d%% | Task: %s | File: %s%n", progressMonitor.getPercentDone(), progressMonitor.getCurrentTask(), progressMonitor.getFileName()); // Update UI progress bar here // progressBar.setValue(progressMonitor.getPercentDone()); Thread.sleep(100); } // Check final result switch (progressMonitor.getResult()) { case SUCCESS: System.out.println("Operation completed successfully!"); break; case ERROR: System.err.println("Error: " + progressMonitor.getException().getMessage()); break; case CANCELLED: System.out.println("Operation was cancelled"); break; default: break; } } catch (ZipException | InterruptedException e) { System.err.println("Error: " + e.getMessage()); } } // Cancel a running operation public void cancelOperation(ZipFile zipFile) { ProgressMonitor pm = zipFile.getProgressMonitor(); pm.setCancelAllTasks(true); } // Pause and resume public void pauseAndResume(ProgressMonitor pm) throws InterruptedException { pm.setPause(true); Thread.sleep(5000); // Paused for 5 seconds pm.setPause(false); } } ``` -------------------------------- ### Zip Compression Method (STORE) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Configures the zip archive to use the 'STORE' compression method, which means no compression is applied. ```APIDOC ## Zip Compression Method (STORE) ### Description Allows creating zip files with no compression (STORE method) instead of the default Deflate. This can be applied to various add operations. ### Method `ZipParameters.setCompressionMethod()` ### Endpoint N/A (Library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(CompressionMethod.STORE); // Example adding a file with STORE compression new ZipFile("filename.zip").addFile("fileToAdd", zipParameters); ``` ### Response #### Success Response (200) N/A (Library method, no explicit HTTP response) #### Response Example N/A ``` -------------------------------- ### Add Empty Folder to Zip Archive with ZipOutputStream (Java) Source: https://github.com/srikanth-lingala/zip4j/blob/master/README.md Illustrates how to add an empty folder to a zip archive using ZipOutputStream. This is achieved by setting the folder name in ZipParameters to end with a forward slash. ```java // To add an empty folder to the zip, make sure the name ends with a / zipParameters.setFileNameInZip("empty folder/"); zipOutputStream.putNextEntry(zipParameters); zipOutputStream.closeEntry(); ```