我正在尝试从AWS开发工具包V1.x迁移到V2.2。不过,我找不到 deleteObjects 方法。我发现了一堆示例-都是相同的:-(似乎从未使用过对象列表进行删除(即存在该列表,但从未在 DeleteObjectsRequest 中设置)对象-我假定应该在此处设置对象,但看不到哪里。如何/在何处提供对象列表?我找到的示例是:
System.out.println("Deleting objects from S3 bucket: " + bucket_name);
for (String k : object_keys) {
System.out.println(" * " + k);
}
Region region = Region.US_WEST_2;
S3Client s3 = S3Client.builder().region(region).build();
try {
DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
.bucket(bucket_name)
.build();
s3.deleteObjects(dor);
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
答案 0 :(得分:3)
看起来需要更多对象才能在s3中分配该对象的键。这未经测试,我将指向方法的链接放在最后。
System.out.println("Deleting objects from S3 bucket: " + bucket_name);
for (String k : object_keys) {
System.out.println(" * " + k);
}
Region region = Region.US_WEST_2;
S3Client s3 = S3Client.builder().region(region).build();
try {
ObjectIdentifier objectToDelete = ObjectIdentifier.Builder()
.key(KEY_OBJECT_TO_DELETE);
Delete delete_me Delete.Builder.objects(objectToDelete)
DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
.bucket(bucket_name)
.delete(delete_me)
.build();
s3.deleteObjects(dor);
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
答案 1 :(得分:0)
即使不是100%完整,以前接受的答案也很有帮助。我用它编写了以下方法。尽管我还没有对它的错误处理进行特别好的测试,但是它基本上可以正常工作。
String
个键的数组,并将其转换为ObjectIdentifier
所需要的是deleteObjects
。s3Client
和log
已在其他地方初始化。如果不需要,请随时删除日志。该方法当前返回成功删除的次数。
public int deleteS3Objects(String bucketName, String[] keys) {
List<ObjectIdentifier> objIds = Arrays.stream(keys)
.map(key -> ObjectIdentifier.builder().key(key).build())
.collect(Collectors.toList());
try {
DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
.bucket(bucketName)
.delete(Delete.builder().objects(objIds).build())
.build();
DeleteObjectsResponse delResp = s3client.deleteObjects(dor);
if (delResp.errors().size() > 0) {
String err = String.format("%d errors returned while deleting %d objects",
delResp.errors().size(), objIds.size());
log.warn(err);
}
if (delResp.deleted().size() < objIds.size()) {
String err = String.format("%d of %d objects deleted",
delResp.deleted().size(), objIds.size());
log.warn(err);
}
return delResp.deleted().size();
}
catch(AwsServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
log.error("Error received from S3 while attempting to delete objects", e);
}
catch(SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
log.error("Exception occurred while attempting to delete objects from S3", e);
}
return 0;
}
(随意的评论:我发现在AWS开发工具包v2.3.9中,deleteObjects
需要Delete.Builder
和ObjectIdentifier
键,但是getObject
和putObject
接受却很奇怪字符串键。DeleteObjectsRequest.Builder
为什么不只有keys()
方法呢?他们还没有正式说SDK是可用于生产的AFAIK,所以其中的某些内容可能会发生变化。)