我试图删除我的s3存储桶中的对象,当它们达到一定限度后说大约20个对象。我在Java SDK中使用了这段代码。
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 s3 = new AmazonS3Client(credentials);
String bucketName = "testbucket";
System.out.println("Listing objects");
ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName);
ObjectListing objectListing = s3.listObjects(listObjectsRequest);
int count = 0;
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
count = count + 1;
if (count < 20)
{
System.out.println("Keep Counting");
}
else {
String key = objectSummary.getKey();
s3.deleteObject(bucketName, key);
}
}
}
}
但是这只会删除前20个对象之后的那些对象。但是,一旦桶中的对象数量超过20+,我希望在s3中删除所有文件。我该怎么做谢谢你的帮助。
答案 0 :(得分:0)
你需要在你的循环之外检查size > 20
。此外,一次可以提取的最大摘要数为1000 - 因此,您需要检查是否有更多摘要,将其拉出并删除它们。
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 s3 = new AmazonS3Client(credentials);
String bucketName = "testbucket";
System.out.println("Listing objects");
ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName);
ObjectListing objectListing = s3.listObjects(listObjectsRequest);
int count = 0;
List<S3ObjectSummary> summaries = objectListing.getObjectSummaries();
if(summaries.size() > 20) // Delete only when the size of bucket is > 20
{
for(;;)
{
for (S3ObjectSummary objectSummary : summaries)
{
String key = objectSummary.getKey();
s3.deleteObject(bucketName, key);
}
if(!objectListing.isTruncated()) // Max of 1000 summaries are fetched in 1 pull
{
break;
}
objectListing = s3.listNextBatchOfObjects(objectListing);
summaries = objectListing.getObjectSummaries();
}
}