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 way to compress multiple files into a single zip file using a simple API call. This tutorial will guide you through the process of sending an API call to zip files using Java, making it easier to manage and share collections of files programmatically.

A user might need to compress files to reduce storage space or to simplify the sharing of multiple files. For example, a company might need to send a batch of reports to a client. By zipping these files, they can be sent as a single attachment, ensuring that all files are received together and reducing the risk of files being lost or overlooked.

Zip Files with Java Code Example

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import okhttp3.*;

public class Zip {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", "file1.txt",
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                new File("file1.txt")))
                .addFormDataPart("file", "file2.txt",
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                new File("file2.txt")))
                .build();
        Request request = new Request.Builder()
                .url("https://api.pdfrest.com/zip")
                .method("POST", body)
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN")
                .build();
        try {
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Source: GitHub Repository

Breaking Down the Code

The code begins by importing necessary classes, including OkHttpClient for making HTTP requests. The OkHttpClient instance is created to handle the HTTP request.

OkHttpClient client = new OkHttpClient().newBuilder().build();

Next, a MediaType object is defined to specify the type of data being sent. Here, "text/plain" is used as a placeholder.

MediaType mediaType = MediaType.parse("text/plain");

The RequestBody is constructed using MultipartBody.Builder to include multiple files. Each file is added with addFormDataPart, specifying the file's name and content type.

RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
        .addFormDataPart("file", "file1.txt",
                RequestBody.create(MediaType.parse("application/octet-stream"),
                        new File("file1.txt")))
        .addFormDataPart("file", "file2.txt",
                RequestBody.create(MediaType.parse("application/octet-stream"),
                        new File("file2.txt")))
        .build();

The Request object is created with the target URL, HTTP method, and headers. The "Authorization" header requires a valid access token.

Request request = new Request.Builder()
        .url("https://api.pdfrest.com/zip")
        .method("POST", body)
        .addHeader("Accept", "application/json")
        .addHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN")
        .build();

Finally, the request is executed, and the response is printed. Exception handling is included to manage potential IO errors.

try {
    Response response = client.newCall(request).execute();
    System.out.println(response.body().string());
} catch (IOException e) {
    e.printStackTrace();
}

Beyond the Tutorial

This tutorial demonstrated how to use the pdfRest Zip Files API Tool to compress files using Java. By following these steps, you can integrate file zipping functionality into your Java applications. To explore further, try out all of the pdfRest API Tools in the API Lab. For more detailed information, refer to the API Reference Guide.

Note: This example demonstrates a multipart API call. For examples using JSON payloads, visit the GitHub Repository.

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