我正在尝试从 AWS SDK V1.x 迁移到 V2.2。我想不通 删除对象 方法虽然。我发现了一堆例子 - 都是一样的 :-( 似乎从来没有使用过要删除的对象列表(即该列表存在,但从未在 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);
}
最佳答案
先前接受的答案非常有帮助,即使它不是 100% 完整。我用它写了下面的方法。虽然我没有特别好地测试它的错误处理,但它基本上有效。
String
的数组传入keys,转换成数组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 SDK v2.3.9 中,
deleteObjects
需要 Delete.Builder
和 ObjectIdentifier
键,但 getObject
和 putObject
接受字符串键。为什么没有 7 |1045| DeleteObjectsRequest.Builder
方法?他们还没有正式说 SDK 是生产就绪的 AFAIK,所以其中一些可能会发生变化。)
关于amazon-s3 - 使用 AWS SDK V2 删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950202/