删除桶

您可以使用 deleteBucket 接口删除桶,以下代码展示如何删除一个桶:

String bucketName = "<your-bucket-name>";
try {
    s3.deleteBucket(bucketName);
} catch (AmazonServiceException e) {
    System.err.println(e.getErrorMessage());
}

在删除桶前,必须先确保桶为空,否则会导致错误。

如果需要删除的桶不为空,需要在删除桶前删除该桶中所有的对象,示例代码如下:

ObjectListing objectListing = s3.listObjects(bucketName);
while (true) {
   Iterator<S3ObjectSummary> objIter = objectListing.getObjectSummaries().iterator();
   while (objIter.hasNext()) {
       s3.deleteObject(bucketName, objIter.next().getKey());
   }

   if (objectListing.isTruncated()) {
       objectListing = s3.listNextBatchOfObjects(objectListing);
   } else {
       break;
   }
}

如果需要删除的桶开启了版本控制,需要在删除桶前删除所有的对象版本,示例代码如下:

VersionListing versionList = s3.listVersions(new ListVersionsRequest().withBucketName(bucketName));
while (true) {
    Iterator<S3VersionSummary> versionIter = versionList.getVersionSummaries().iterator();
    while (versionIter.hasNext()) {
        S3VersionSummary vs = versionIter.next();
        s3.deleteVersion(bucketName, vs.getKey(), vs.getVersionId());
    }

    if (versionList.isTruncated()) {
        versionList = s3.listNextBatchOfVersions(versionList);
    } else {
        break;
   }
}