Amazon Simple Storage Service
开发人员指南 (API Version 2006-03-01)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。点 击 Getting Started with Amazon AWS to see specific differences applicable to the China (Beijing) Region.

使用AWS SDK for Java删除多个对象

以下任务将指导您完成使用AWS SDK for Java类在单个 HTTP 请求中删除多个对象的过程。

删除多个对象 (不受版本控制的存储桶)

1

创建 AmazonS3Client 类的实例。

2

创建 DeleteObjectsRequest 类的实例并提供要删除的对象键的列表。

3

执行 AmazonS3Client.deleteObjects 方法。

下面的 Java 代码示例演示了上述步骤。

Copy
DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucketName); List<KeyVersion> keys = new ArrayList<KeyVersion>(); keys.add(new KeyVersion(keyName1)); keys.add(new KeyVersion(keyName2)); keys.add(new KeyVersion(keyName3)); multiObjectDeleteRequest.setKeys(keys); try { DeleteObjectsResult delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest); System.out.format("Successfully deleted all the %s items.\n", delObjRes.getDeletedObjects().size()); } catch (MultiObjectDeleteException e) { // Process exception. }

在发生异常的情况下,您可以查看 MultiObjectDeleteException 以确定哪些对象未能删除及其原因,如下面的 Java 示例中所示。

Copy
System.out.format("%s \n", e.getMessage()); System.out.format("No. of objects successfully deleted = %s\n", e.getDeletedObjects().size()); System.out.format("No. of objects failed to delete = %s\n", e.getErrors().size()); System.out.format("Printing error data...\n"); for (DeleteError deleteError : e.getErrors()){ System.out.format("Object Key: %s\t%s\t%s\n", deleteError.getKey(), deleteError.getCode(), deleteError.getMessage()); }

下面的任务将引导您完成从受版本控制的存储桶删除对象的过程。

删除多个对象 (启用了版本的存储桶)

1

创建 AmazonS3Client 类的实例。

2

创建 DeleteObjectsRequest 类的实例并提供对象键的列表,同时选择性地提供要删除的对象的版本 ID。

如果您指定了要删除的对象的版本 ID,Amazon S3 将删除特定的对象版本。如果您没有指定要删除的对象的版本 ID,则 Amazon S3 将添加一个删除标记。有关更多信息,请参阅 每个请求删除一个对象。

3

执行 AmazonS3Client.deleteObjects 方法。

下面的 Java 代码示例演示了上述步骤。

Copy
List<KeyVersion> keys = new ArrayList<KeyVersion>(); // Provide a list of object keys and versions. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucketName) .withKeys(keys); try { DeleteObjectsResult delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest); System.out.format("Successfully deleted all the %s items.\n", delObjRes.getDeletedObjects().size()); } catch (MultiObjectDeleteException e) { // Process exception. }

例 1:多对象删除 (不受版本控制的存储桶)

下面的 Java 代码示例使用多对象删除 API 以便从不受版本控制的存储桶删除对象。该示例首先将示例对象上传到存储桶,然后使用 deleteObjects 方法删除单个请求中的对象。

有关如何创建和测试有效示例的信息,请参阅 测试 Java 代码示例

Copy
import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.DeleteObjectsRequest; import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion; import com.amazonaws.services.s3.model.DeleteObjectsResult; import com.amazonaws.services.s3.model.MultiObjectDeleteException; import com.amazonaws.services.s3.model.MultiObjectDeleteException.DeleteError; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.PutObjectResult; public class DeleteMultipleObjectsNonVersionedBucket { static String bucketName = "*** Provide a bucket name ***"; static AmazonS3Client s3Client; public static void main(String[] args) throws IOException { try { s3Client = new AmazonS3Client(new ProfileCredentialsProvider()); // Upload sample objects.Because the bucket is not version-enabled, // the KeyVersions list returned will have null values for version IDs. List<KeyVersion> keysAndVersions1 = putObjects(3); // Delete specific object versions. multiObjectNonVersionedDelete(keysAndVersions1); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException."); System.out.println("Error Message: " + ace.getMessage()); } } static List<KeyVersion> putObjects(int number) { List<KeyVersion> keys = new ArrayList<KeyVersion>(); String content = "This is the content body!"; for (int i = 0; i < number; i++) { String key = "ObjectToDelete-" + new Random().nextInt(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setHeader("Subject", "Content-As-Object"); metadata.setHeader("Content-Length", (long)content.length()); PutObjectRequest request = new PutObjectRequest(bucketName, key, new ByteArrayInputStream(content.getBytes()), metadata) .withCannedAcl(CannedAccessControlList.AuthenticatedRead); PutObjectResult response = s3Client.putObject(request); KeyVersion keyVersion = new KeyVersion(key, response.getVersionId()); keys.add(keyVersion); } return keys; } static void multiObjectNonVersionedDelete(List<KeyVersion> keys) { // Multi-object delete by specifying only keys (no version ID). DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest( bucketName).withQuiet(false); // Create request that include only object key names. List<KeyVersion> justKeys = new ArrayList<KeyVersion>(); for (KeyVersion key : keys) { justKeys.add(new KeyVersion(key.getKey())); } multiObjectDeleteRequest.setKeys(justKeys); // Execute DeleteObjects - Amazon S3 add delete marker for each object // deletion. The objects no disappear from your bucket (verify). DeleteObjectsResult delObjRes = null; try { delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest); System.out.format("Successfully deleted all the %s items.\n", delObjRes.getDeletedObjects().size()); } catch (MultiObjectDeleteException mode) { printDeleteResults(mode); } } static void printDeleteResults(MultiObjectDeleteException mode) { System.out.format("%s \n", mode.getMessage()); System.out.format("No. of objects successfully deleted = %s\n", mode.getDeletedObjects().size()); System.out.format("No. of objects failed to delete = %s\n", mode.getErrors().size()); System.out.format("Printing error data...\n"); for (DeleteError deleteError : mode.getErrors()){ System.out.format("Object Key: %s\t%s\t%s\n", deleteError.getKey(), deleteError.getCode(), deleteError.getMessage()); } } }

例 2:多对象删除 (启用了版本的存储桶)

下面的 Java 代码示例使用多对象删除 API 以从受版本控制的存储桶删除对象。

测试示例之前,您必须创建一个示例存储桶并在示例中提供存储桶名称。可以使用 AWS 管理控制台创建存储桶。

该示例将执行以下操作:

  1. 对存储桶启用版本控制功能。

  2. 执行受版本控制的删除。

    该示例首先会上传示例对象。作为响应,Amazon S3 将为您上传的每个示例对象返回版本 ID。然后,该示例会使用多对象删除 API 删除这些对象。在请求中,它会指定对象键和版本 ID (即,受版本控制的删除)。

  3. 执行不受版本控制的删除。

    该示例将上传新的示例对象。然后,它会使用多对象 API 删除对象。但是,在请求中,它仅指定对象键。在此例中,Amazon S3 会添加删除标记并且对象会从您的存储桶中消失。

  4. 删除这些删除标记。

    为了演示删除标记的工作方式,示例将删除这些删除标记。在多对象删除请求中,示例会指定上一步骤中其在响应中收到的删除标记的对象键和版本 ID。此操作使对象再度出现在存储桶中。

有关如何创建和测试有效示例的信息,请参阅 测试 Java 代码示例

Copy
import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.BucketVersioningConfiguration; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.DeleteObjectsRequest; import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion; import com.amazonaws.services.s3.model.DeleteObjectsResult; import com.amazonaws.services.s3.model.DeleteObjectsResult.DeletedObject; import com.amazonaws.services.s3.model.MultiObjectDeleteException; import com.amazonaws.services.s3.model.MultiObjectDeleteException.DeleteError; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.SetBucketVersioningConfigurationRequest; public class DeleteMultipleObjectsVersionEnabledBucket { static String bucketName = "*** Provide a bucket name ***"; static AmazonS3Client s3Client; public static void main(String[] args) throws IOException { try { s3Client = new AmazonS3Client(new ProfileCredentialsProvider()); // 1. Enable versioning on the bucket. enableVersioningOnBucket(s3Client, bucketName); // 2a. Upload sample objects. List<KeyVersion> keysAndVersions1 = putObjects(3); // 2b. Delete specific object versions. multiObjectVersionedDelete(keysAndVersions1); // 3a. Upload samples objects. List<KeyVersion> keysAndVersions2 = putObjects(3); // 3b. Delete objects using only keys. Amazon S3 creates a delete marker and // returns its version Id in the response. DeleteObjectsResult response = multiObjectNonVersionedDelete(keysAndVersions2); // 3c. Additional exercise - using multi-object versioned delete, remove the // delete markers received in the preceding response. This results in your objects // reappear in your bucket multiObjectVersionedDeleteRemoveDeleteMarkers(response); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException."); System.out.println("Error Message: " + ace.getMessage()); } } static void enableVersioningOnBucket(AmazonS3Client s3Client, String bucketName) { BucketVersioningConfiguration config = new BucketVersioningConfiguration() .withStatus(BucketVersioningConfiguration.ENABLED); SetBucketVersioningConfigurationRequest setBucketVersioningConfigurationRequest = new SetBucketVersioningConfigurationRequest( bucketName, config); s3Client.setBucketVersioningConfiguration(setBucketVersioningConfigurationRequest); } static List<KeyVersion> putObjects(int number) { List<KeyVersion> keys = new ArrayList<KeyVersion>(); String content = "This is the content body!"; for (int i = 0; i < number; i++) { String key = "ObjectToDelete-" + new Random().nextInt(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setHeader("Subject", "Content-As-Object"); metadata.setHeader("Content-Length", (long)content.length()); PutObjectRequest request = new PutObjectRequest(bucketName, key, new ByteArrayInputStream(content.getBytes()), metadata) .withCannedAcl(CannedAccessControlList.AuthenticatedRead); PutObjectResult response = s3Client.putObject(request); KeyVersion keyVersion = new KeyVersion(key, response.getVersionId()); keys.add(keyVersion); } return keys; } static void multiObjectVersionedDelete(List<KeyVersion> keys) { DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest( bucketName).withKeys(keys); DeleteObjectsResult delObjRes = null; try { delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest); System.out.format("Successfully deleted all the %s items.\n", delObjRes.getDeletedObjects().size()); } catch(MultiObjectDeleteException mode) { printDeleteResults(mode); } } static DeleteObjectsResult multiObjectNonVersionedDelete(List<KeyVersion> keys) { // Multi-object delete by specifying only keys (no version ID). DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest( bucketName); // Create request that include only object key names. List<KeyVersion> justKeys = new ArrayList<KeyVersion>(); for (KeyVersion key : keys) { justKeys.add(new KeyVersion(key.getKey())); } multiObjectDeleteRequest.setKeys(justKeys); // Execute DeleteObjects - Amazon S3 add delete marker for each object // deletion. The objects no disappear from your bucket (verify). DeleteObjectsResult delObjRes = null; try { delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest); System.out.format("Successfully deleted all the %s items.\n", delObjRes.getDeletedObjects().size()); } catch (MultiObjectDeleteException mode) { printDeleteResults(mode); } return delObjRes; } static void multiObjectVersionedDeleteRemoveDeleteMarkers( DeleteObjectsResult response) { List<KeyVersion> keyVersionList = new ArrayList<KeyVersion>(); for (DeletedObject deletedObject : response.getDeletedObjects()) { keyVersionList.add(new KeyVersion(deletedObject.getKey(), deletedObject.getDeleteMarkerVersionId())); } // Create a request to delete the delete markers. DeleteObjectsRequest multiObjectDeleteRequest2 = new DeleteObjectsRequest( bucketName).withKeys(keyVersionList); // Now delete the delete marker bringing your objects back to the bucket. DeleteObjectsResult delObjRes = null; try { delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest2); System.out.format("Successfully deleted all the %s items.\n", delObjRes.getDeletedObjects().size()); } catch (MultiObjectDeleteException mode) { printDeleteResults(mode); } } static void printDeleteResults(MultiObjectDeleteException mode) { System.out.format("%s \n", mode.getMessage()); System.out.format("No. of objects successfully deleted = %s\n", mode.getDeletedObjects().size()); System.out.format("No. of objects failed to delete = %s\n", mode.getErrors().size()); System.out.format("Printing error data...\n"); for (DeleteError deleteError : mode.getErrors()){ System.out.format("Object Key: %s\t%s\t%s\n", deleteError.getKey(), deleteError.getCode(), deleteError.getMessage()); } } }