2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaでAWS S3オブジェクトの削除

Last updated at Posted at 2020-06-04

AWS SDK for Javaを利用して、S3オブジェクトの削除ができます。

#1つのオブジェクトの削除
bucket名とオブジェクトキーを指定すれば、指定オブジェクトの削除ができます。

try {
    final AmazonS3 s3 = new AmazonS3Client();
    s3.deleteObject(bucket_name, object_key);
} catch (AmazonServiceException e) {
    e.printStackTrace();
}

#指定フォルダーにある全てのオブジェクトの削除
bucket名とフォルダー名を指定すれば、指定フォルダーにある全てのオブジェクトの削除ができます。

try {
    final AmazonS3 s3 = new AmazonS3Client();
  ObjectListing objListing = s3.listObjects(bucket_name,folder_nm);
    List<S3ObjectSummary> objList = objListing.getObjectSummaries();
    for (S3ObjectSummary obj : objList) {
         s3.deleteObject(bucket_name, obj.getKey());
    }
} catch (AmazonServiceException e) {
    e.printStackTrace();
}

s3.listObjectsは以下のようなポリシー設定は必要。

PolicyDocument:
      Version: 2012-10-17
      Statement:
        - Effect: Allow
          Action: "s3:*"
          Resource:
            - "arn:aws:s3:::bucket-test-01"
            - "arn:aws:s3:::bucket-test-01/*"
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?