如何使用 AWS Java SDK 清空 Amazon S3 Bucket?

How to empty Amazon S3 Bucket using AWS Java SDK?

我无法在 Java 中找到有关如何以编程方式清空 Amazon S3 存储桶的任何文档。任何帮助将不胜感激。

要使用 Java 删除 Amazon S3 对象,您可以使用 AWS SDK for Java V2。要清空存储桶,首先使用以下代码获取存储桶中所有对象的列表:

public static void listBucketObjects(S3Client s3, String bucketName ) {

       try {
            ListObjectsRequest listObjects = ListObjectsRequest
                    .builder()
                    .bucket(bucketName)
                    .build();

            ListObjectsResponse res = s3.listObjects(listObjects);
            List<S3Object> objects = res.contents();

            for (ListIterator iterVals = objects.listIterator(); iterVals.hasNext(); ) {
                S3Object myValue = (S3Object) iterVals.next();
                System.out.print("\n The name of the key is " + myValue.key());
                System.out.print("\n The object is " + calKb(myValue.size()) + " KBs");
                System.out.print("\n The owner is " + myValue.owner());

             }

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

对于每个对象,您可以使用以下代码将其删除:

 public static void deleteBucketObjects(S3Client s3, String bucketName, String objectName) {

    ArrayList<ObjectIdentifier> toDelete = new ArrayList<ObjectIdentifier>();
    toDelete.add(ObjectIdentifier.builder().key(objectName).build());

    try {
        DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
                .bucket(bucketName)
                .delete(Delete.builder().objects(toDelete).build())
                .build();
        s3.deleteObjects(dor);
    } catch (S3Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}

您可以在 AWS Github 此处找到这些示例和许多其他示例:

Amazon S3 Java code examples