How to Zip Files with Java

Learn how to compress files into a Zip archive using the pdfRest Zip Files API Tool with Java
Share this page

Why Zip Files with Java?

The pdfRest Zip Files API Tool provides a convenient and efficient way to compress multiple files into a single ZIP archive using Java. This tutorial will guide you through the process of sending an API call to zip files using Java, leveraging the capabilities of the pdfRest API to streamline file management tasks.

In real-world scenarios, users might need to compress multiple documents into a single ZIP file for easier storage or sharing. For instance, a business might need to send a collection of PDF reports to a client. By zipping these files, the business can reduce the file size and simplify the transfer process, ensuring that all necessary documents are delivered together.

Zip Files with Java Code Example

import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import okhttp3.*;
import org.json.JSONObject;

public class Zip {

  // Specify the paths to your file here, or as the arguments when running the program.
  private static final String[] DEFAULT_FILE_PATHS =
      new String[] {"/path/to/file1.pdf", "/path/to/file2.pdf"};

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    String[] inputFilePaths;
    if (args.length > 0) {
      inputFilePaths = args;
    } else {
      inputFilePaths = DEFAULT_FILE_PATHS;
    }

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

    for (String inputFilePath : inputFilePaths) {
      final File inputFile = new File(inputFilePath);
      final RequestBody inputFileRequestBody =
          RequestBody.create(inputFile, MediaType.parse("application/pdf"));
      bodyBuilder.addFormDataPart("file", inputFile.getName(), inputFileRequestBody);
    }

    RequestBody requestBody = bodyBuilder.addFormDataPart("output", "pdfrest_zip").build();

    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url("https://api.pdfrest.com/zip")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client = new OkHttpClient().newBuilder().build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

Source: GitHub

Breaking Down the Code

The code begins by importing necessary libraries, including OkHttp for HTTP requests and Dotenv for environment variable management. The DEFAULT_FILE_PATHS array specifies the file paths to be zipped, and DEFAULT_API_KEY holds the API key, which can also be set via environment variables.

The main method checks if file paths are provided as arguments; otherwise, it uses the default paths. It then loads environment variables using Dotenv. A MultipartBody.Builder is initialized to construct the request body, specifying the type as MultipartBody.FORM.

For each file path, a File object is created, and a RequestBody is built with the file's content type set to application/pdf. These are added to the form data part of the request body using addFormDataPart.

The request body is completed by adding an output form data part with the value pdfrest_zip. A Request object is then created, setting the Api-Key header and specifying the URL https://api.pdfrest.com/zip for the POST request.

An OkHttpClient executes the request, and the response is printed. The prettyJson method formats the JSON response for readability.

Beyond the Tutorial

This tutorial demonstrated how to use Java to send an API call to compress files using the pdfRest Zip Files API Tool. By following these steps, you can efficiently manage and share multiple files in a compressed format.

To explore more functionalities, try out all the pdfRest API Tools in the API Lab. For detailed information, refer to the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found here.

Generate a self-service API Key now!

Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.

Compare Plans
Contact Us