文档基于2025-10-10日社区最终版构建     
切换到英文版    进入演示系统    进入交流社区

MinIO Documentation

Java 快速入门指南

Java Client API ReferenceSlack

创建 MinIO 客户端。

MinIO

MinioClient minioClient =
    MinioClient.builder()
        .endpoint("https://play.min.io")
        .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
        .build();

AWS S3

MinioClient minioClient =
    MinioClient.builder()
        .endpoint("https://s3.amazonaws.com")
        .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
        .build();

Bucket operations

对象操作

bucketExists

composeObject

deleteBucketEncryption

copyObject

deleteBucketLifecycle

deleteObjectTags

deleteBucketNotification

disableObjectLegalHold

deleteBucketPolicy

downloadObject

deleteBucketReplication

enableObjectLegalHold

deleteBucketTags

getObject

deleteObjectLockConfiguration

getObjectRetention

getBucketEncryption

getObjectTags

getBucketLifecycle

getPresignedObjectUrl

getBucketNotification

getPresignedPostFormData

getBucketPolicy

isObjectLegalHoldEnabled

getBucketReplication

listObjects

getBucketTags

putObject

getBucketVersioning

removeObject

getObjectLockConfiguration

removeObjects

listBuckets

selectObjectContent

listenBucketNotification

setObjectRetention

makeBucket

setObjectTags

removeBucket

statObject

setBucketEncryption

uploadObject

setBucketLifecycle

uploadSnowballObjects

setBucketNotification

setBucketPolicy

setBucketReplication

setBucketTags

setBucketVersioning

setObjectLockConfiguration

1. MinIO Client Builder

MinIO Client Builder 用于创建 MinIO 客户端。Builder 提供以下方法来接收参数。

方法

描述

endpoint()

接受端点作为字符串、URL 或 okhttp3.HttpUrl 对象,并可选择接受端口号和启用安全(TLS)连接的标志。

端点作为字符串可以按以下格式表示:

https://s3.amazonaws.com

https://play.min.io

https://play.min.io:9000

localhost

play.min.io

credentials()

接受 S3 服务中账户的访问密钥(即用户 ID)和秘密密钥(即密码)。

region()

接受 S3 服务的区域名称。如果指定,所有操作将使用此区域,否则将按存储桶探测区域。

httpClient()

自定义 HTTP 客户端以覆盖默认设置。

示例

MinIO

// 1. Create client to S3 service 'play.min.io' at port 443 with TLS security
// for anonymous access.
MinioClient minioClient = MinioClient.builder().endpoint("https://play.min.io").build();

// 2. Create client to S3 service 'play.min.io' at port 443 with TLS security
// using URL object for anonymous access.
MinioClient minioClient = MinioClient.builder().endpoint(new URL("https://play.min.io")).build();

// 3. Create client to S3 service 'play.min.io' at port 9000 with TLS security
// using okhttp3.HttpUrl object for anonymous access.
MinioClient minioClient =
    MinioClient.builder().endpoint(HttpUrl.parse("https://play.min.io:9000")).build();

// 4. Create client to S3 service 'play.min.io' at port 443 with TLS security
// for authenticated access.
MinioClient minioClient =
    MinioClient.builder()
            .endpoint("https://play.min.io")
                .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
                .build();

// 5. Create client to S3 service 'play.min.io' at port 9000 with non-TLS security
// for authenticated access.
MinioClient minioClient =
    MinioClient.builder()
            .endpoint("play.min.io", 9000, false)
            .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
                .build();

// 6. Create client to S3 service 'play.min.io' at port 9000 with TLS security
// for authenticated access.
MinioClient minioClient =
    MinioClient.builder()
            .endpoint("play.min.io", 9000, true)
                .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
                .build();

// 7. Create client to S3 service 'play.min.io' at port 443 with TLS security
// and region 'us-west-1' for authenticated access.
MinioClient minioClient =
    MinioClient.builder()
            .endpoint(new URL("https://play.min.io"))
                .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
                .region("us-west-1")
                .build();

// 8. 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();

AWS S3

// 1. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security
// for anonymous access.
MinioClient s3Client = MinioClient.builder().endpoint("https://s3.amazonaws.com").build();

// 2. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security
// using URL object for anonymous access.
MinioClient s3Client = MinioClient.builder().endpoint(new URL("https://s3.amazonaws.com")).build();

// 3. Create client to S3 service 's3.amazonaws.com' at port 9000 with TLS security
// using okhttp3.HttpUrl object for anonymous access.
MinioClient s3Client =
    MinioClient.builder().endpoint(HttpUrl.parse("https://s3.amazonaws.com")).build();

// 4. Create client to S3 service 's3.amazonaws.com' at port 80 with TLS security
// for authenticated access.
MinioClient s3Client =
    MinioClient.builder()
            .endpoint("s3.amazonaws.com")
                .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
                .build();

// 5. Create client to S3 service 's3.amazonaws.com' at port 443 with non-TLS security
// for authenticated access.
MinioClient s3Client =
    MinioClient.builder()
        .endpoint("s3.amazonaws.com", 433, false)
                .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
                .build();

// 6. Create client to S3 service 's3.amazonaws.com' at port 80 with non-TLS security
// for authenticated access.
MinioClient s3Client =
    MinioClient.builder()
            .endpoint("s3.amazonaws.com", 80, false)
        .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
                .build();

// 7. Create client to S3 service 's3.amazonaws.com' at port 80 with TLS security
// for authenticated access.
MinioClient s3Client =
    MinioClient.builder()
            .endpoint("s3.amazonaws.com", 80, true)
        .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
                .build();

// 8. Create client to S3 service 's3.amazonaws.com' at port 80 with non-TLS security
// and region 'us-west-1' for authenticated access.
MinioClient s3Client =
    MinioClient.builder()
            .endpoint("s3.amazonaws.com", 80, false)
        .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
                .region("us-west-1")
                .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();

// 10. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security,
// region 'eu-central-1' and custom HTTP client for authenticated access.
MinioClient s3Client =
    MinioClient.builder()
            .endpoint("s3.amazonaws.com", 443, true)
        .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY")
                .region("eu-central-1")
                .httpClient(customHttpClient)
                .build();

常见异常

所有API除了特定于API的异常外,还会抛出以下异常。

异常

原因

ErrorResponseException

抛出此异常表示 S3 服务返回了错误响应。

IllegalArgumentException

抛出以表示传入了无效参数。

InsufficientDataException

抛出此异常表示 InputStream 中没有足够的数据可用。

内部异常

表示内部库错误。

InvalidKeyException

抛出此异常表示缺少 HMAC SHA-256 库。

InvalidResponseException

抛出此异常表示 S3 服务返回了无效或无错误响应。

IOException

抛出以指示 S3 操作发生 I/O 错误。

NoSuchAlgorithmException

抛出此异常表示缺少 MD5 或 SHA-256 摘要库。

ServerException

表示HTTP服务器错误。

XmlParserException

表示 XML 解析错误。

2. 存储桶操作

bucketExists(BucketExistsArgs args)

public boolean bucketExists(BucketExistsArgs args) [Javadoc]

检查存储桶是否存在。

参数

参数

类型

描述

bucketName

BucketExistsArgs

参数。

返回

boolean- 如果存储桶存在则为 True。

Example

// Check whether 'my-bucketname' exists or not.
boolean found =
  minioClient.bucketExists(BucketExistsArgs.builder().bucket("my-bucketname").build());
if (found) {
  System.out.println("my-bucketname exists");
} else {
  System.out.println("my-bucketname does not exist");
}

deleteBucketEncryption(DeleteBucketEncryptionArgs args)

private void deleteBucketEncryption(DeleteBucketEncryptionArgs args) [Javadoc]

删除存储桶的加密配置。

参数

参数

类型

描述

args

DeleteBucketEncryptionArgs

参数。

Example

minioClient.deleteBucketEncryption(
    DeleteBucketEncryptionArgs.builder().bucket("my-bucketname").build());

deleteBucketLifecycle(DeleteBucketLifecycleArgs args)

private void deleteBucketLifecycle(DeleteBucketLifecycleArgs args) [Javadoc]

删除存储桶的生命周期配置。

参数

参数

类型

描述

args

DeleteBucketLifecycleArgs

参数。

Example

minioClient.deleteBucketLifecycle(
    DeleteBucketLifecycleArgs.builder().bucket("my-bucketname").build());

deleteBucketTags(DeleteBucketTagsArgs args)

private void deleteBucketTags(DeleteBucketTagsArgs args) [Javadoc]

删除存储桶的标签。

参数

参数

类型

描述

args

DeleteBucketTagsArgs

参数。

Example

minioClient.deleteBucketTags(DeleteBucketTagsArgs.builder().bucket("my-bucketname").build());

deleteBucketPolicy(DeleteBucketPolicyArgs args)

private void deleteBucketPolicy(DeleteBucketPolicyArgs args) [Javadoc]

删除存储桶的存储桶策略配置。

参数

参数

类型

描述

args

DeleteBucketPolicyArgs

参数。

Example

minioClient.deleteBucketPolicy(DeleteBucketPolicyArgs.builder().bucket("my-bucketname").build());

deleteBucketReplication(DeleteBucketReplicationArgs args)

private void deleteBucketReplication(DeleteBucketReplicationArgs args) [Javadoc]

删除存储桶的复制配置。

参数

参数

类型

描述

args

DeleteBucketReplicationArgs

参数。

Example

minioClient.deleteBucketReplication(
    DeleteBucketReplicationArgs.builder().bucket("my-bucketname").build());

deleteBucketNotification(DeleteBucketNotificationArgs args)

public void deleteBucketNotification(DeleteBucketNotificationArgs args) [Javadoc]

删除存储桶的通知配置。

参数

参数

类型

描述

args

DeleteBucketNotificationArgs

参数。

Example

minioClient.deleteBucketNotification(
    DeleteBucketNotificationArgs.builder().bucket("my-bucketname").build());

deleteObjectLockConfiguration(DeleteObjectLockConfigurationArgs args)

public void deleteObjectLockConfiguration(DeleteObjectLockConfigurationArgs args) [Javadoc]

删除存储桶中的对象锁定配置。

参数

参数

类型

描述

args

DeleteObjectLockConfigurationArgs

参数。

Example

minioClient.deleteObjectLockConfiguration(
    DeleteObjectLockConfigurationArgs.builder().bucket("my-bucketname").build());

getBucketEncryption(GetBucketEncryptionArgs args)

public SseConfiguration getBucketEncryption(GetBucketEncryptionArgs args) [Javadoc]

获取存储桶的加密配置。

参数

参数

类型

描述

args

GetBucketEncryptionArgs

参数。

返回

SseConfiguration- 服务器端加密配置。

Example

SseConfiguration config =
    minioClient.getBucketEncryption(
        GetBucketEncryptionArgs.builder().bucket("my-bucketname").build());

getBucketLifecycle(GetBucketLifecycleArgs args)

public LifecycleConfiguration getBucketLifecycle(GetBucketLifecycleArgs args) [Javadoc]

获取存储桶的生命周期配置。

参数

参数

类型

描述

args

GetBucketLifecycleArgs

参数。

返回

生命周期配置- 生命周期配置。

Example

LifecycleConfiguration config =
    minioClient.getBucketLifecycle(
            GetBucketLifecycleArgs.builder().bucket("my-bucketname").build());
System.out.println("Lifecycle configuration: " + config);

getBucketNotification(GetBucketNotificationArgs args)

public NotificationConfiguration getBucketNotification(GetBucketNotificationArgs args) [Javadoc]

获取存储桶的通知配置。

参数

参数

类型

描述

args

GetBucketNotificationArgs

参数。

返回

通知配置- 通知配置。

Example

NotificationConfiguration config =
    minioClient.getBucketNotification(
            GetBucketNotificationArgs.builder().bucket("my-bucketname").build());

getBucketPolicy(GetBucketPolicyArgs args)

public String getBucketPolicy(GetBucketPolicyArgs args) [Javadoc]

获取存储桶的策略配置。

参数

参数

类型

描述

args

GetBucketPolicyArgs

参数。

返回

字符串- 存储桶策略配置,以 JSON 字符串形式表示。

Example

String config =
    minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket("my-bucketname").build());

getBucketReplication(GetBucketReplicationArgs args)

public ReplicationConfiguration getBucketReplication(GetBucketReplicationArgs args) [Javadoc]

获取存储桶的复制配置。

参数

参数

类型

描述

args

GetBucketReplicationArgs

参数。

返回

复制配置- 存储桶复制配置。

Example

ReplicationConfiguration config =
    minioClient.getBucketReplication(
            GetBucketReplicationArgs.builder().bucket("my-bucketname").build());

getBucketTags(GetBucketTagsArgs args)

public Tags getBucketTags(GetBucketTagsArgs args) [Javadoc]

获取存储桶的标签。

参数

参数

类型

描述

args

GetBucketTagsArgs

参数。

返回

标签- 标签。

Example

Tags tags = minioClient.getBucketTags(GetBucketTagsArgs.builder().bucket("my-bucketname").build());

getBucketVersioning(GetBucketVersioningArgs args)

public VersioningConfiguration getBucketVersioning(GetBucketVersioningArgs args) [Javadoc]

获取存储桶的版本控制配置。

参数

参数

类型

描述

args

GetBucketVersioningArgs

参数。

返回

VersioningConfiguration- 版本控制配置。

Example

VersioningConfiguration config =
    minioClient.getBucketVersioning(
        GetBucketVersioningArgs.builder().bucket("my-bucketname").build());

getObjectLockConfiguration(GetObjectLockConfigurationArgs args)

public ObjectLockConfiguration getObjectLockConfiguration(GetObjectLockConfigurationArgs args) [Javadoc]

获取存储桶中的对象锁定配置。

参数

参数

类型

描述

args

GetObjectLockConfigurationArgs

参数。

返回

ObjectLockConfiguration- 默认保留配置。

Example

ObjectLockConfiguration config =
    minioClient.getObjectLockConfiguration(
            GetObjectLockConfigurationArgs.builder().bucket("my-bucketname").build());
System.out.println("Mode: " + config.mode());
System.out.println("Duration: " + config.duration().duration() + " " + config.duration().unit());

listBuckets()

public List<Bucket> listBuckets() [Javadoc]

列出所有存储桶的存储桶信息。

返回

List<>- 存储桶信息列表。

Example

List<Bucket> bucketList = minioClient.listBuckets();
for (Bucket bucket : bucketList) {
  System.out.println(bucket.creationDate() + ", " + bucket.name());
}

listBuckets(ListBucketsArgs args)

public List<Bucket> listBuckets(ListBucketsArgs args) [Javadoc]

列出所有存储桶的存储桶信息。

参数

参数

类型

描述

args

ListBucketsArgs

参数。

返回

List<>- 存储桶信息列表。

Example

List<Bucket> bucketList =
    minioClient.listBuckets(ListBuckets.builder().extraHeaders(headers).build());
for (Bucket bucket : bucketList) {
  System.out.println(bucket.creationDate() + ", " + bucket.name());
}

listenBucketNotification(ListenBucketNotificationArgs args)

public CloseableIterator<Result<NotificationRecords>> listenBucketNotification(ListenBucketNotificationArgs args) [Javadoc]

监听存储桶中对象前缀和后缀的事件。返回的可关闭迭代器采用惰性求值,因此需要遍历才能获取新记录,并且必须与 try-with-resource 一起使用以释放底层网络资源。

参数

参数

类型

描述

args

ListenBucketNotificationArgs

参数。

返回

CloseableIterator<结果<通知记录>>- 惰性可关闭迭代器包含事件记录。

Example

String[] events = {"s3:ObjectCreated:*", "s3:ObjectAccessed:*"};
try (CloseableIterator<Result<NotificationRecords>> ci =
    minioClient.listenBucketNotification(
        ListenBucketNotificationArgs.builder()
            .bucket("bucketName")
            .prefix("")
            .suffix("")
            .events(events)
            .build())) {
  while (ci.hasNext()) {
    NotificationRecords records = ci.next().get();
    for (Event event : records.events()) {
      System.out.println("Event " + event.eventType() + " occurred at " + event.eventTime()
          + " for " + event.bucketName() + "/" + event.objectName());
    }
  }
}

listObjects(ListObjectsArgs args)

public Iterable<Result<Item>> listObjects(ListObjectsArgs args) [Javadoc]

列出存储桶中的对象信息。

参数

参数

类型

描述

args

ListObjectsArgs

列出对象的参数

返回

Iterable<结果<项目>>- 惰性迭代器包含对象信息。

Example

// Lists objects information.
Iterable<Result<Item>> results = minioClient.listObjects(
    ListObjectsArgs.builder().bucket("my-bucketname").build());

// Lists objects information recursively.
Iterable<Result<Item>> results = 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>> results = 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>> results = minioClient.listObjects(
    ListObjectsArgs.builder()
        .bucket("my-bucketname")
        .startAfter("ExampleGuide.pdf")
        .prefix("E")
        .maxKeys(100)
        .includeVersions(true)
        .build());

makeBucket(MakeBucketArgs args)

public void makeBucket(MakeBucketArgs args) [Javadoc]

在指定区域创建一个启用了对象锁定功能的存储桶。

参数

参数

类型

描述

args

MakeBucketArgs

创建存储桶的参数

Example

// 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());

removeBucket(RemoveBucketArgs args)

public void removeBucket(RemoveBucketArgs args) [Javadoc]

删除一个空桶。

参数

参数

类型

描述

args

RemoveBucketArgs

参数。

Example

minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());

setBucketEncryption(SetBucketEncryptionArgs args)

public void setBucketEncryption(SetBucketEncryptionArgs args) [Javadoc]

设置存储桶的加密配置。

参数

参数

类型

描述

args

SetBucketEncryptionArgs

参数。

Example

minioClient.setBucketEncryption(
    SetBucketEncryptionArgs.builder().bucket("my-bucketname").config(config).build());

setBucketLifecycle(SetBucketLifecycleArgs args)

public void setBucketLifecycle(SetBucketLifecycleArgs args) [Javadoc]

设置存储桶的生命周期配置。

参数

参数

类型

描述

args

SetBucketLifecycleArgs

参数。

Example

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());

setBucketNotification(SetBucketNotificationArgs args)

public void setBucketNotification(SetBucketNotificationArgs args) [Javadoc]

设置存储桶的通知配置。

参数

参数

类型

描述

args

SetBucketNotificationArgs

参数。

Example

List<EventType> eventList = new LinkedList<>();
eventList.add(EventType.OBJECT_CREATED_PUT);
eventList.add(EventType.OBJECT_CREATED_COPY);

QueueConfiguration queueConfiguration = new QueueConfiguration();
queueConfiguration.setQueue("arn:minio:sqs::1:webhook");
queueConfiguration.setEvents(eventList);
queueConfiguration.setPrefixRule("images");
queueConfiguration.setSuffixRule("pg");

List<QueueConfiguration> queueConfigurationList = new LinkedList<>();
queueConfigurationList.add(queueConfiguration);

NotificationConfiguration config = new NotificationConfiguration();
config.setQueueConfigurationList(queueConfigurationList);

minioClient.setBucketNotification(
    SetBucketNotificationArgs.builder().bucket("my-bucketname").config(config).build());

setBucketPolicy(SetBucketPolicyArgs args)

public void setBucketPolicy(SetBucketPolicyArgs args) [Javadoc]

设置存储桶策略配置到存储桶。

参数

参数

类型

描述

args

SetBucketPolicyArgs

参数。

Example

// Assume policyJson contains below JSON string;
// {
//     "Statement": [
//         {
//             "Action": [
//                 "s3:GetBucketLocation",
//                 "s3:ListBucket"
//             ],
//             "Effect": "Allow",
//             "Principal": "*",
//             "Resource": "arn:aws:s3:::my-bucketname"
//         },
//         {
//             "Action": "s3:GetObject",
//             "Effect": "Allow",
//             "Principal": "*",
//             "Resource": "arn:aws:s3:::my-bucketname/myobject*"
//         }
//     ],
//     "Version": "2012-10-17"
// }
//
minioClient.setBucketPolicy(
    SetBucketPolicyArgs.builder().bucket("my-bucketname").config(policyJson).build());

setBucketReplication(SetBucketReplicationArgs args)

public void setBucketReplication(SetBucketReplicationArgs args) [Javadoc]

设置存储桶的复制配置。

参数

参数

类型

描述

args

SetBucketReplicationArgs

参数。

Example

Map<String, String> tags = new HashMap<>();
tags.put("key1", "value1");
tags.put("key2", "value2");

ReplicationRule rule =
    new ReplicationRule(
        new DeleteMarkerReplication(Status.DISABLED),
        new ReplicationDestination(
            null, null, "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", null, null, null, null),
        null,
        new RuleFilter(new AndOperator("TaxDocs", tags)),
        "rule1",
        null,
        1,
        null,
        Status.ENABLED);

List<ReplicationRule> rules = new LinkedList<>();
rules.add(rule);

ReplicationConfiguration config =
    new ReplicationConfiguration("REPLACE-WITH-ACTUAL-ROLE", rules);

minioClient.setBucketReplication(
    SetBucketReplicationArgs.builder().bucket("my-bucketname").config(config).build());

setBucketTags(SetBucketTagsArgs args)

public void setBucketTags(SetBucketTagsArgs args) [Javadoc]

为存储桶设置标签。

参数

参数

类型

描述

args

SetBucketTagsArgs

参数。

Example

Map<String, String> map = new HashMap<>();
map.put("Project", "Project One");
map.put("User", "jsmith");
minioClient.setBucketTags(SetBucketTagsArgs.builder().bucket("my-bucketname").tags(map).build());

setBucketVersioning(SetBucketVersioningArgs args)

public void setBucketVersioning(SetBucketVersioningArgs args) [Javadoc]

设置存储桶的版本控制配置。

参数

参数

类型

描述

args

SetBucketVersioningArgs

参数。

Example

minioClient.setBucketVersioning(
    SetBucketVersioningArgs.builder().bucket("my-bucketname").config(config).build());

setObjectLockConfiguration(SetObjectLockConfigurationArgs args)

public void setObjectLockConfiguration(SetObjectLockConfigurationArgs args) [Javadoc]

设置存储桶中的对象锁定配置。

参数

参数

类型

描述

args

SetObjectLockConfigurationArgs

参数。

Example

ObjectLockConfiguration config =
    new ObjectLockConfiguration(RetentionMode.COMPLIANCE, new RetentionDurationDays(100));
minioClient.setObjectLockConfiguration(
    SetObjectLockConfigurationArgs.builder().bucket("my-bucketname").config(config).build());

3. Object operations

composeObject(ComposeObjectArgs args)

public ObjectWriteResponse composeObject(ComposeObjectArgs args) [Javadoc]

通过使用服务器端复制,将来自不同源对象的数据组合创建一个对象。

参数

Param

类型

描述

args

ComposeObjectArgs

参数。

返回

ObjectWriteResponse- 包含已创建对象的信息。

Example

List<ComposeSource> sourceObjectList = new ArrayList<ComposeSource>();
sourceObjectList.add(
 ComposeSource.builder().bucket("my-job-bucket").object("my-objectname-part-one").build());
sourceObjectList.add(
 ComposeSource.builder().bucket("my-job-bucket").object("my-objectname-part-two").build());
sourceObjectList.add(
 ComposeSource.builder().bucket("my-job-bucket").object("my-objectname-part-three").build());

// Create my-bucketname/my-objectname by combining source object list.
minioClient.composeObject(
 ComposeObjectArgs.builder()
     .bucket("my-bucketname")
     .object("my-objectname")
     .sources(sourceObjectList)
     .build());

// Create my-bucketname/my-objectname with user metadata by combining source object
// list.
Map<String, String> userMetadata = new HashMap<>();
userMetadata.put("My-Project", "Project One");
minioClient.composeObject(
   ComposeObjectArgs.builder()
     .bucket("my-bucketname")
     .object("my-objectname")
     .sources(sourceObjectList)
     .userMetadata(userMetadata)
     .build());

// Create my-bucketname/my-objectname with user metadata and server-side encryption
// by combining source object list.
minioClient.composeObject(
 ComposeObjectArgs.builder()
     .bucket("my-bucketname")
     .object("my-objectname")
     .sources(sourceObjectList)
     .userMetadata(userMetadata)
     .ssec(sse)
     .build());

copyObject(CopyObjectArgs args)

public ObjectWriteResponse copyObject(CopyObjectArgs args) [Javadoc]

通过服务器端从另一个对象复制数据来创建对象。

参数

参数

类型

描述

args

CopyObjectArgs

参数。

返回

ObjectWriteResponse- 包含已创建对象的信息。

Example

// 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());

// Create object "my-objectname" in bucket "my-bucketname" by copying from object
// "my-source-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-source-objectname")
                .build())
        .build());

// Create object "my-objectname" in bucket "my-bucketname" with SSE-KMS server-side
// encryption 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())
        .sse(sseKms) // Replace with actual key.
        .build());

// Create object "my-objectname" in bucket "my-bucketname" with SSE-S3 server-side
// encryption 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())
        .sse(sseS3) // Replace with actual key.
        .build());

// Create object "my-objectname" in bucket "my-bucketname" with SSE-C server-side encryption
// 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())
        .sse(ssec) // Replace with actual key.
        .build());

// Create object "my-objectname" in bucket "my-bucketname" by copying from SSE-C encrypted
// object "my-source-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-source-objectname")
                .ssec(ssec) // Replace with actual key.
                .build())
        .build());

// Create object "my-objectname" in bucket "my-bucketname" with custom headers conditionally
// 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")
                .matchETag(etag) // Replace with actual etag.
                .build())
        .headers(headers) // Replace with actual headers.
        .build());

deleteObjectTags(DeleteObjectTagsArgs args)

private void deleteObjectTags(DeleteObjectTagsArgs args) [Javadoc]

删除对象的标签。

参数

参数

类型

描述

args

DeleteObjectTagsArgs

参数。

Example

minioClient.deleteObjectTags(
    DeleteObjectArgs.builder().bucket("my-bucketname").object("my-objectname").build());

disableObjectLegalHold(DisableObjectLegalHoldArgs args)

public void disableObjectLegalHold(DisableObjectLegalHoldArgs args) [Javadoc]

禁用对象的法律保留。

参数

参数

类型

描述

args

DisableObjectLegalHoldArgs

参数。

Example

// Disables legal hold on an object.
minioClient.disableObjectLegalHold(
    DisableObjectLegalHoldArgs.builder()
        .bucket("my-bucketname")
        .object("my-objectname")
        .build());

enableObjectLegalHold(EnableObjectLegalHoldArgs args)

public void enableObjectLegalHold(EnableObjectLegalHoldArgs args) [Javadoc]

对对象启用法律保留。

参数

参数

类型

描述

args

EnableObjectLegalHoldArgs

参数。

Example

// Disables legal hold on an object.
minioClient.enableObjectLegalHold(
   EnableObjectLegalHoldArgs.builder()
       .bucket("my-bucketname")
       .object("my-objectname")
       .build());

getObject(GetObjectArgs args)

public InputStream getObject(GetObjectArgs args) [Javadoc]

获取对象的数据。返回InputStream使用后必须关闭以释放网络资源。

参数

参数

类型

描述

args

GetObjectArgs

参数。

返回

输入流- 包含对象数据。

Example

// get object given the bucket and object name
try (InputStream stream = minioClient.getObject(
  GetObjectArgs.builder()
  .bucket("my-bucketname")
  .object("my-objectname")
  .build())) {
  // Read data from stream
}

// get object data from offset
try (InputStream stream = minioClient.getObject(
  GetObjectArgs.builder()
  .bucket("my-bucketname")
  .object("my-objectname")
  .offset(1024L)
  .build())) {
  // Read data from stream
}

// get object data from offset to length
try (InputStream stream = minioClient.getObject(
  GetObjectArgs.builder()
  .bucket("my-bucketname")
  .object("my-objectname")
  .offset(1024L)
  .length(4096L)
  .build())) {
  // Read data from stream
}

// get data of an SSE-C encrypted object
try (InputStream stream = minioClient.getObject(
  GetObjectArgs.builder()
  .bucket("my-bucketname")
  .object("my-objectname")
  .ssec(ssec)
  .build())) {
  // Read data from stream
}

// get object data from offset to length of an SSE-C encrypted object
try (InputStream stream = minioClient.getObject(
  GetObjectArgs.builder()
  .bucket("my-bucketname")
  .object("my-objectname")
  .offset(1024L)
  .length(4096L)
  .ssec(ssec)
  .build())) {
  // Read data from stream
}

downloadObject(DownloadObjectArgs args)

public void downloadObject(DownloadObjectArgs args) [Javadoc]

将对象的数据下载到文件。

参数

参数

类型

描述

args

DownloadObjectArgs

参数。

Example

// Download object given the bucket, object name and output file name
minioClient.downloadObject(
  DownloadObjectArgs.builder()
  .bucket("my-bucketname")
  .object("my-objectname")
  .filename("my-object-file")
  .build());

// Download server-side encrypted object in bucket to given file name
minioClient.downloadObject(
  DownloadObjectArgs.builder()
  .bucket("my-bucketname")
  .object("my-objectname")
  .ssec(ssec)
  .filename("my-object-file")
  .build());

getObjectRetention(GetObjectRetentionArgs args)

public Retention getObjectRetention(GetObjectRetentionArgs args) [Javadoc]

获取对象的保留配置。

参数

参数

类型

描述

args

GetObjectRetentionArgs

参数。

返回

留存率- 对象保留配置。

Example

// Object with version id.
Retention retention =
   minioClient.getObjectRetention(
       GetObjectRetentionArgs.builder()
           .bucket("my-bucketname")
           .object("my-objectname")
           .versionId("object-version-id")
           .build());
System.out.println("mode: " + retention.mode() + "until: " + retention.retainUntilDate());

getObjectTags(GetObjectTagsArgs args)

public Tags getObjectTags(GetObjectTagsArgs args) [Javadoc]

获取对象的标签。

参数

参数

类型

描述

args

GetObjectTagsArgs

参数。

返回

标签- 标签。

Example

Tags tags = minioClient.getObjectTags(
    GetObjectTagsArgs.builder().bucket("my-bucketname").object("my-objectname").build());

getPresignedObjectUrl(GetPresignedObjectUrlArgs args)

public String getPresignedObjectUrl(GetPresignedObjectUrlArgs args) [Javadoc]

获取对象的预签名URL,用于HTTP方法、过期时间和自定义请求参数。

参数

参数

类型

描述

args

GetPresignedObjectUrlArgs

参数。

返回

字符串- URL 字符串。

Example

// Get presigned URL string to download 'my-objectname' in 'my-bucketname'
// with an expiration of 2 hours.
//
// Additionally also add 'response-content-type' to dynamically set content-type
// for the server response.
Map<String, String> reqParams = new HashMap<String, String>();
reqParams.put("response-content-type", "application/json");

String url =
   minioClient.getPresignedObjectUrl(
       GetPresignedObjectUrlArgs.builder()
           .method(Method.GET)
           .bucket("my-bucketname")
           .object("my-objectname")
           .expiry(2, TimeUnit.HOURS)
           .extraQueryParams(reqParams)
           .build());
System.out.println(url);

// Get presigned URL string to upload 'my-objectname' in 'my-bucketname'
// with an expiration of 1 day.
String url =
   minioClient.getPresignedObjectUrl(
       GetPresignedObjectUrlArgs.builder()
           .method(Method.PUT)
           .bucket("my-bucketname")
           .object("my-objectname")
           .expiry(1, TimeUnit.DAYS)
           .build());
System.out.println(url);

// Get presigned URL string to lookup metadata for 'my-objectname' in 'my-bucketname'
// with an expiration of 2 hours.
//
// Additionally also add 'response-content-type' to dynamically set content-type
// for the server metadata response.
Map<String, String> reqParams = new HashMap<String, String>();
reqParams.put("response-content-type", "application/json");

String url =
   minioClient.getPresignedObjectUrl(
       GetPresignedObjectUrlArgs.builder()
           .method(Method.HEAD)
           .bucket("my-bucketname")
           .object("my-objectname")
           .expiry(2, TimeUnit.HOURS)
           .extraQueryParams(reqParams)
           .build());
System.out.println(url);

isObjectLegalHoldEnabled(IsObjectLegalHoldEnabledArgs args)

public boolean isObjectLegalHoldEnabled(IsObjectLegalHoldEnabledArgs args) [Javadoc]

如果对象启用了合法保留,则返回 true。

参数

参数

类型

描述

args

IsObjectLegalHoldEnabledArgs

参数。

返回

boolean- 如果启用了合法保留,则为 True。

Example

boolean status =
    s3Client.isObjectLegalHoldEnabled(
       IsObjectLegalHoldEnabledArgs.builder()
            .bucket("my-bucketname")
            .object("my-objectname")
            .versionId("object-versionId")
            .build());
if (status) {
  System.out.println("Legal hold is on");
else {
  System.out.println("Legal hold is off");
}

getPresignedPostFormData(PostPolicy policy)

public Map<String,String> getPresignedPostFormData(PostPolicy policy) [Javadoc]

获取表单数据PostPolicy使用POST方法上传对象数据。

参数

参数

类型

描述

policy

PostPolicy

对象的发布策略。

返回

Map<String, String>- 包含使用POST方法上传对象所需的表单数据。

Example

// Create new post policy for 'my-bucketname' with 7 days expiry from now.
PostPolicy policy = new PostPolicy("my-bucketname", ZonedDateTime.now().plusDays(7));

// Add condition that 'key' (object name) equals to 'my-objectname'.
policy.addEqualsCondition("key", "my-objectname");

// Add condition that 'Content-Type' starts with 'image/'.
policy.addStartsWithCondition("Content-Type", "image/");

// Add condition that 'content-length-range' is between 64kiB to 10MiB.
policy.addContentLengthRangeCondition(64 * 1024, 10 * 1024 * 1024);

Map<String, String> formData = minioClient.getPresignedPostFormData(policy);

// Upload an image using POST object with form-data.
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
for (Map.Entry<String, String> entry : formData.entrySet()) {
  multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
multipartBuilder.addFormDataPart("key", "my-objectname");
multipartBuilder.addFormDataPart("Content-Type", "image/png");

// "file" must be added at last.
multipartBuilder.addFormDataPart(
    "file", "my-objectname", RequestBody.create(new File("Pictures/avatar.png"), null));

Request request =
    new Request.Builder()
        .url("https://play.min.io/my-bucketname")
        .post(multipartBuilder.build())
        .build();
OkHttpClient httpClient = new OkHttpClient().newBuilder().build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
  System.out.println("Pictures/avatar.png is uploaded successfully using POST object");
} else {
  System.out.println("Failed to upload Pictures/avatar.png");
}

putObject(PutObjectArgs args)

public ObjectWriteResponse putObject(PutObjectArgs args) [Javadoc]

将给定流作为对象上传到存储桶中。

参数

参数

类型

描述

args

PutObjectArgs

参数。

返回

ObjectWriteResponse- 包含已创建对象的信息。

Example

// Upload known sized input stream.
minioClient.putObject(
    PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream(
            inputStream, size, -1)
        .contentType("video/mp4")
        .build());

// Upload unknown sized input stream.
minioClient.putObject(
    PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream(
            inputStream, -1, 10485760)
        .contentType("video/mp4")
        .build());

// Create object ends with '/' (also called as folder or directory).
minioClient.putObject(
    PutObjectArgs.builder().bucket("my-bucketname").object("path/to/").stream(
            new ByteArrayInputStream(new byte[] {}), 0, -1)
        .build());

// Upload input stream with headers and user metadata.
Map<String, String> headers = new HashMap<>();
headers.put("X-Amz-Storage-Class", "REDUCED_REDUNDANCY");
Map<String, String> userMetadata = new HashMap<>();
userMetadata.put("My-Project", "Project One");
minioClient.putObject(
    PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream(
            inputStream, size, -1)
        .headers(headers)
        .userMetadata(userMetadata)
        .build());

// Upload input stream with server-side encryption.
minioClient.putObject(
    PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream(
            inputStream, size, -1)
        .sse(sse)
        .build());

uploadObject(UploadObjectArgs args)

public void uploadObject(UploadObjectArgs args) [Javadoc]

将文件内容作为对象上传到存储桶中。

参数

参数

类型

描述

args

UploadObjectArgs

参数。

Example

// Upload an JSON file.
minioClient.uploadObject(
    UploadObjectArgs.builder()
        .bucket("my-bucketname").object("my-objectname").filename("person.json").build());

// Upload a video file.
minioClient.uploadObject(
    UploadObjectArgs.builder()
        .bucket("my-bucketname")
        .object("my-objectname")
        .filename("my-video.avi")
        .contentType("video/mp4")
        .build());

uploadSnowballObjects(UploadSnowballObjectsArgs args)

public void uploadSnowballObjects(UploadSnowballObjectsArgs args) [Javadoc]

在单个上传请求中上传多个对象。这是通过创建可选的压缩中间TAR文件,并将其上传到S3服务来实现的。

参数

参数

类型

描述

args

UploadSnowballObjectsArgs

参数。

Example

List<SnowballObject> objects = new ArrayList<SnowballObject>();
objects.add(
    new SnowballObject(
        "my-object-one",
        new ByteArrayInputStream("hello".getBytes(StandardCharsets.UTF_8)),
        5,
        null));
objects.add(
    new SnowballObject(
        "my-object-two",
        new ByteArrayInputStream("java".getBytes(StandardCharsets.UTF_8)),
        4,
        null));
minioClient.uploadSnowballObjects(
    UploadSnowballObjectsArgs.builder().bucket("my-bucketname").objects(objects).build());

removeObject(RemoveObjectArgs args)

public void removeObject(RemoveObjectArgs args) [Javadoc]

删除一个对象。

参数

参数

类型

描述

args

RemoveObjectArgs

参数。

Example

// Remove object.
minioClient.removeObject(
    RemoveObjectArgs.builder().bucket("my-bucketname").object("my-objectname").build());

// Remove versioned object.
minioClient.removeObject(
    RemoveObjectArgs.builder()
        .bucket("my-bucketname")
        .object("my-versioned-objectname")
        .versionId("my-versionid")
        .build());

// Remove versioned object bypassing Governance mode.
minioClient.removeObject(
    RemoveObjectArgs.builder()
        .bucket("my-bucketname")
        .object("my-versioned-objectname")
        .versionId("my-versionid")
        .bypassRetentionMode(true)
        .build());

removeObjects(RemoveObjectsArgs args)

public Iterable<Result<DeleteError>> removeObjects(RemoveObjectsArgs args) [Javadoc]

延迟删除多个对象。需要遍历返回的 Iterable 才能执行删除操作。

参数

参数

类型

描述

args

RemoveObjectsArgs

参数。

返回

Iterable<结果<删除错误>>- 惰性迭代器包含对象移除状态。

Example

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());
}

selectObjectContent(SelectObjectContentArgs args)

public SelectResponseStream selectObjectContent(SelectObjectContentArgs args) [Javadoc]

通过SQL表达式选择对象的内容。

参数

参数

类型

描述

args

SelectObjectContentArgs

参数。

返回

选择响应流- 包含已筛选的记录和进度。

Example

String sqlExpression = "select * from S3Object";
InputSerialization is = new InputSerialization(null, false, null, null, FileHeaderInfo.USE, null, null, null);
OutputSerialization os = new OutputSerialization(null, null, null, QuoteFields.ASNEEDED, null);
SelectResponseStream stream =
    minioClient.selectObjectContent(
        SelectObjectContentArgs.builder()
            .bucket("my-bucketname")
            .object("my-objectName")
            .sqlExpression(sqlExpression)
            .inputSerialization(is)
            .outputSerialization(os)
            .requestProgress(true)
            .build());

byte[] buf = new byte[512];
int bytesRead = stream.read(buf, 0, buf.length);
System.out.println(new String(buf, 0, bytesRead, StandardCharsets.UTF_8));

Stats stats = stream.stats();
System.out.println("bytes scanned: " + stats.bytesScanned());
System.out.println("bytes processed: " + stats.bytesProcessed());
System.out.println("bytes returned: " + stats.bytesReturned());

stream.close();

setObjectRetention(SetObjectRetentionArgs args)

public void setObjectLockRetention(SetObjectRetentionArgs) [Javadoc]

设置对象的保留配置。

参数

参数

类型

描述

args

SetObjectRetentionArgs

参数。

Example

Retention retention = new Retention(RetentionMode.COMPLIANCE, ZonedDateTime.now().plusYears(1));
minioClient.setObjectRetention(
    SetObjectRetentionArgs.builder()
        .bucket("my-bucketname")
        .object("my-objectname")
        .config(retention)
        .bypassGovernanceMode(true)
        .build());

setObjectTags(SetObjectTagsArgs args)

public void setObjectTags(SetObjectTagsArgs args) [Javadoc]

为对象设置标签。

参数

参数

类型

描述

args

SetObjectTagsArgs

参数。

Example

Map<String, String> map = new HashMap<>();
map.put("Project", "Project One");
map.put("User", "jsmith");
minioClient.setObjectTags(
    SetObjectTagsArgs.builder().bucket("my-bucketname").object("my-objectname").tags(map).build());

statObject(StatObjectArgs args)

public ObjectStat statObject(StatObjectArgs args) [Javadoc]

获取对象信息和对象的元数据。

参数

参数

类型

描述

args

StatObjectArgs

参数。

返回

ObjectStat- 填充的对象信息和元数据。

Example

// Get information of an object.
ObjectStat objectStat =
    minioClient.statObject(
        StatObjectArgs.builder().bucket("my-bucketname").object("my-objectname").build());

// Get information of SSE-C encrypted object.
ObjectStat objectStat =
    minioClient.statObject(
        StatObjectArgs.builder()
            .bucket("my-bucketname")
            .object("my-objectname")
            .ssec(ssec)
            .build());

// Get information of a versioned object.
ObjectStat objectStat =
    minioClient.statObject(
        StatObjectArgs.builder()
            .bucket("my-bucketname")
            .object("my-objectname")
            .versionId("version-id")
            .build());

// Get information of a SSE-C encrypted versioned object.
ObjectStat objectStat =
    minioClient.statObject(
        StatObjectArgs.builder()
            .bucket("my-bucketname")
            .object("my-objectname")
            .versionId("version-id")
            .ssec(ssec)
            .build());

5. 深入探索