MinIO Java SDK Documentation

repository·master·Indexed 23 days ago

https://github.com/minio/minio-java

A client library for performing bucket and object operations on any Amazon S3 compatible cloud storage service. It provides the MinioClient for managing buckets, object uploads and downloads, presigned URLs, and bucket configurations including CORS, encryption, lifecycle, and versioning.

Tokens
10.7K
Snippets
29
Records
41
Agent score
78%

What's inside MinIO Java SDK

  1. Quick Start: Upload a file to MinIO

    master

    To connect to a MinIO service, you need three parameters:

    1. Endpoint: The URL of the object storage service.
    2. Access Key: A unique identifier for your account (like a user ID).
    3. Secret Key: The password for your account.

    This example demonstrates how to initialize a MinioClient, check if a bucket exists, create it if it doesn't, and upload a file using putObject.

    import java.io.IOException;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    
    import org.xmlpull.v1.XmlPullParserException;
    
    import io.minio.MinioClient;
    import io.minio.errors.MinioException;
    
    public class FileUploader {
      public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException {
        try {
          // Create a MinioClient using the service URL, Access key, and Secret key
          MinioClient minioClient = new MinioClient("https://play.min.io", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
    
          // Check if the bucket exists
          boolean isExist = minioClient.bucketExists("asiatrip");
          if(isExist) {
            System.out.println("Bucket already exists.");
          } else {
            // Create a bucket named 'asiatrip'
            minioClient.makeBucket("asiatrip");
          }
    
          // Upload a file to the bucket using putObject
          minioClient.putObject("asiatrip","asiaphotos.zip", "/home/user/Photos/asiaphotos.zip");
          System.out.println("/home/user/Photos/asiaphotos.zip is successfully uploaded as asiaphotos.zip to `asiatrip` bucket.");
        } catch(MinioException e) {
          System.out.println("Error occurred: " + e);
        }
      }
    }
  2. Compile and run the FileUploader example

    master

    To compile and run the provided FileUploader.java using the downloaded JAR file, use the following commands:

    Compile:

    $ javac -cp minio-9.0.3-all.jar FileUploader.java

    Run:

    $ java -cp minio-9.0.3-all.jar:. FileUploader
    ### Compile FileUploader
    ```sh
    $ javac -cp minio-9.0.3-all.jar FileUploader.java

    Run FileUploader

    $ java -cp minio-9.0.3-all.jar:. FileUploader
  3. Install the MinIO Java SDK

    master

    The MinIO Java SDK provides a simple API to access any Amazon S3 compatible object storage service. It requires Java 1.8 or higher.

    You can install it using Maven or Gradle, or by downloading the JAR file directly.

    ### Maven
    ```xml
    <dependency>
        <groupId>io.minio</groupId>
        <artifactId>minio</artifactId>
        <version>3.0.10</version>
    </dependency>

    Gradle

    dependencies {
        implementation("io.minio:minio:3.0.10")
    }
  4. Quick Start: Upload a file to an S3 bucket

    master

    To connect to an S3 compatible service, you need an Endpoint (URL), an Access Key, and a Secret Key.

    This example demonstrates how to use MinioClient to:

    1. Initialize a client using the builder pattern.
    2. Check if a bucket exists using bucketExists and BucketExistsArgs.
    3. Create a bucket if it does not exist using makeBucket and MakeBucketArgs.
    4. Upload a local file to a specific bucket and object name using uploadObject and UploadObjectArgs.
    import io.minio.BucketExistsArgs;
    import io.minio.MakeBucketArgs;
    import io.minio.MinioClient;
    import io.minio.UploadObjectArgs;
    import io.minio.errors.MinioException;
    import java.io.IOException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    
    public class FileUploader {
      public static void main(String[] args)
          throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        try {
          // Create a minioClient with the MinIO server playground, its access key and secret key.
          MinioClient minioClient =
              MinioClient.builder()
                  .endpoint("https://play.min.io")
                  .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
                  .build();
    
          // Make 'asiatrip' bucket if not exist.
          boolean found =
              minioClient.bucketExists(BucketExistsArgs.builder().bucket("asiatrip").build());
          if (!found) {
            // Make a new bucket called 'asiatrip'.
            minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
          } else {
            System.out.println("Bucket 'asiatrip' already exists.");
          }
    
          // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
          // 'asiatrip'.
          minioClient.uploadObject(
              UploadObjectArgs.builder()
                  .bucket("asiatrip")
                  .object("asiaphotos-2015.zip")
                  .filename("/home/user/Photos/asiaphotos.zip")
                  .build());
          System.out.println(
              "'/home/user/Photos/asiaphotos.zip' is successfully uploaded as "
                  + "object 'asiaphotos-2015.zip' to bucket 'asiatrip'.");
        } catch (MinioException e) {
          System.out.println("Error occurred: " + e);
          System.out.println("HTTP trace: " + e.httpTrace());
        }
      }
    }
  5. Configure MinIO Client for AWS S3

    master

    To connect to AWS S3, use the MinioClient.builder() with the S3 endpoint (e.g., s3.amazonaws.com). You can specify the port and TLS settings explicitly. For example, to connect to port 443 with TLS and a specific region:

    MinioClient s3Client =
        MinioClient.builder()
            .endpoint("s3.amazonaws.com", 443, true)
            .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
            .region("eu-west-2")
            .build();
    // 9. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security
    // and region 'eu-west-2' for authenticated access.
    MinioClient s3Client =
        MinioClient.builder()
            .endpoint("s3.amazonaws.com", 443, true)
            .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
            .region("eu-west-2")
            .build();
  6. Remove multiple objects lazily

    master

    Use removeObjects to delete multiple objects. This method returns an Iterable<Result<DeleteError>>. You must iterate through the returned Iterable to actually perform the removal and to check for errors.

    List<DeleteObject> objects = new LinkedList<>();
    objects.add(new DeleteObject("my-objectname1"));
    objects.add(new DeleteObject("my-objectname2"));
    objects.add(new DeleteObject("my-objectname3"));
    Iterable<Result<DeleteError>> results =
        minioClient.removeObjects(
            RemoveObjectsArgs.builder().bucket("my-bucketname").objects(objects).build());
    for (Result<DeleteError> result : results) {
      DeleteError error = result.get();
      System.out.println(
          "Error in deleting object " + error.objectName() + "; " + error.message());
    }
  7. Configure bucket lifecycle

    master

    Manage lifecycle rules (e.g., transitions to Glacier or expirations) using setBucketLifecycle(SetBucketLifecycleArgs args) and getBucketLifecycle(GetBucketLifecycleArgs args). To delete the configuration, use deleteBucketLifecycle(DeleteBucketLifecycleArgs args).

    // Set lifecycle configuration
    List<LifecycleRule> rules = new LinkedList<>();
    rules.add(
        new LifecycleRule(
            Status.ENABLED,
            null,
            null,
            new RuleFilter("documents/"),
            "rule1",
            null,
            null,
            new Transition((ZonedDateTime) null, 30, "GLACIER")));
    rules.add(
        new LifecycleRule(
            Status.ENABLED,
            null,
            new Expiration((ZonedDateTime) null, 365, null),
            new RuleFilter("logs/"),
            "rule2",
            null,
            null,
            null));
    LifecycleConfiguration config = new LifecycleConfiguration(rules);
    minioClient.setBucketLifecycle(
        SetBucketLifecycleArgs.builder().bucket("my-bucketname").config(config).build());
    
    // Get lifecycle configuration
    LifecycleConfiguration retrievedConfig =
        minioClient.getBucketLifecycle(GetBucketLifecycleArgs.builder().bucket("my-bucketname").build());
  8. Copy an object using server-side copy

    master

    Use copyObject to create a new object by copying data from an existing source object. This supports copying within the same bucket or across different buckets, applying SSE (KMS, S3, or C), and using conditional headers like matchETag.

    // Create object "my-objectname" in bucket "my-bucketname" by copying from object
    // "my-objectname" in bucket "my-source-bucketname".
    minioClient.copyObject(
        CopyObjectArgs.builder()
            .bucket("my-bucketname")
            .object("my-objectname")
            .source(
                CopySource.builder()
                    .bucket("my-source-bucketname")
                    .object("my-objectname")
                    .build())
            .build());
  9. Create a MinIO Client using MinIOClient.builder()

    master

    Use the MinIOClient.builder() to instantiate a MinioClient. The builder provides several methods to configure the connection to your S3-compatible storage:

    • endpoint(...): Configures the service endpoint. It accepts a String (e.g., https://play.min.io), a java.net.URL object, or an okhttp3.HttpUrl object. You can also provide a host, port, and a boolean flag for TLS (e.g., .endpoint("play.min.io", 9000, true)).
    • credentials(accessKey, secretKey): Provides the access key (user ID) and secret key (password) for authenticated access.
    • region(regionName): Sets the S3 region. If not specified, the region is probed per bucket.
    • httpClient(customHttpClient): Allows overriding the default HTTP client with a custom one.
    // Create client to S3 service 'play.min.io' at port 9000 with TLS security,
    // region 'eu-east-1' and custom HTTP client for authenticated access.
    MinioClient minioClient =
        MinioClient.builder()
            .endpoint("https://play.min.io:9000")
            .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
            .region("eu-east-1")
            .httpClient(customHttpClient)
            .build();
  10. Create a bucket

    master

    Use makeBucket(MakeBucketArgs args) to create a new bucket. You can specify a default region, a specific region, or enable the object lock feature during creation.

    // Create bucket with default region.
    minioClient.makeBucket(
        MakeBucketArgs.builder()
            .bucket("my-bucketname")
            .build());
    
    // Create bucket with specific region.
    minioClient.makeBucket(
        MakeBucketArgs.builder()
            .bucket("my-bucketname")
            .region("us-west-1")
            .build());
    
    // Create object-lock enabled bucket with specific region.
    minioClient.makeBucket(
        MakeBucketArgs.builder()
            .bucket("my-bucketname")
            .region("us-west-1")
            .objectLock(true)
            .build());
  11. List objects in a bucket

    master

    Use listObjects(ListObjectsArgs args) to retrieve object information. This method returns a lazy Iterable<Result<Item>>. You can perform recursive listing, filter by prefix, set a starting point with startAfter, limit results with maxKeys, or include object versions.

    // Lists objects information.
    Iterable<Result<Item>> results = minioClient.listObjects(
        ListObjectsArgs.builder().bucket("my-bucketname").build());
    
    // Lists objects information recursively.
    Iterable<Result<Item>> resultsRecursive = minioClient.listObjects(
        ListObjectsArgs.builder().bucket("my-bucketname").recursive(true).build());
    
    // Lists maximum 100 objects information whose names starts with 'E' and after 'ExampleGuide.pdf'.
    Iterable<Result<Item>> resultsFiltered = minioClient.listObjects(
        ListObjectsArgs.builder()
            .bucket("my-bucketname")
            .startAfter("ExampleGuide.pdf")
            .prefix("E")
            .maxKeys(100)
            .build());
    
    // Lists maximum 100 objects information with version whose names starts with 'E' and after 'ExampleGuide.pdf'.
    Iterable<Result<Item>> resultsWithVersions = minioClient.listObjects(
        ListObjectsArgs.builder()
            .bucket("my-bucketname")
            .startAfter("ExampleGuide.pdf")
            .prefix("E")
            .maxKeys(100)
            .includeVersions(true)
            .build());