I had a requirement like that in my work, so I implemented it.
It was unexpectedly troublesome to think that I could write in one or two lines ... The library uses Guava and lombok. (Unfortunately my workplace is Java 7) I think there is a better way, but it worked for the time being, so make a note
S3ObjectDelete.java
@RequiredArgsConstructor
public class S3ObjectDelete {
private AmazonS3Client client = new AmazonS3Client();
private final String bucket;
public static void main(String[] args) {
val hoge = new S3ObjectDelete("Bucket name");
hoge.delete("Prefix");
}
public void delete(String prefix) {
//It seems that the maximum number of items that can be deleted at the same time is 1000, so divide and process
for (val keys : Lists.partition(keys(prefix), 1000)) {
String[] array = keys.toArray(new String[keys.size()]);
client.deleteObjects(new DeleteObjectsRequest(bucket).withKeys(array));
}
}
List<String> keys(String prefix) {
ObjectListing objects = client.listObjects(bucket, prefix);
val f = new S3Object2StringKey();
List<String> keys = new ArrayList<>(Lists.transform(objects.getObjectSummaries(), f));
//It seems that the default number of items that can be acquired at one time is 1000, so loop and acquire all
while (objects.isTruncated()) {
objects = client.listNextBatchOfObjects(objects);
keys.addAll(Lists.transform(objects.getObjectSummaries(), f));
}
return keys;
}
}
public static class S3Object2StringKey implements Function<S3ObjectSummary, String> {
@Override
public String apply(S3ObjectSummary input) {
return input.getKey();
}
}
** Amazon S3 Client ** has been deprecated Seems to recommend using AmazonS3ClientBuilder This article was helpful.
Recommended Posts