删除文件夹及其内容 AWS S3 java

Delete a folder and its content AWS S3 java

是否可以使用 java sdk for aws 通过单个 api 请求删除文件夹(在 S3 存储桶中)及其所有内容。对于浏览器控制台,我们只需单击一下即可删除文件夹及其内容,我希望使用 API 也能实现相同的行为。

S3中没有文件夹之类的东西;只有文件名中带有斜杠的文件。

浏览器控制台会将这些斜杠可视化为文件夹,但它们不是真实的。

您可以删除所有具有相同前缀的文件,但您需要先使用list_objects()查找它们,然后您才能批量删除它们。

使用 Java sdk 的代码片段请参考下面的文档

http://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingJava.html

您可以在 ListObjectsRequest 中指定 keyPrefix。

例如,考虑包含以下键的存储桶:

  • foo/bar/baz
  • foo/bar/bash
  • foo/bar/bang
  • foo/boo

并且您想从 foo/bar/baz.

中删除文件
if (s3Client.doesBucketExist(bucketName)) {
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
                .withBucketName(bucketName)
                .withPrefix("foo/bar/baz");

        ObjectListing objectListing = s3Client.listObjects(listObjectsRequest);

        while (true) {
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                s3Client.deleteObject(bucketName, objectSummary.getKey());
            }
            if (objectListing.isTruncated()) {
                objectListing = s3Client.listNextBatchOfObjects(objectListing);
            } else {
                break;
            }
        }
    }

https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/ListObjectsRequest.html

在 java sdk 中没有提供文件夹名称或更具体的前缀来删除文件的选项。但是可以选择提供要删除的键数组。 Click for details . 利用这个,我写了一个小方法,可以删除某个前缀对应的所有文件。

private AmazonS3 s3client = <Your s3 client>;
private String bucketName = <your bucket name, can be signed or unsigned>;

public void deleteDirectory(String prefix) {
    ObjectListing objectList = this.s3client.listObjects( this.bucketName, prefix );
    List<S3ObjectSummary> objectSummeryList =  objectList.getObjectSummaries();
    String[] keysList = new String[ objectSummeryList.size() ];
    int count = 0;
    for( S3ObjectSummary summery : objectSummeryList ) {
        keysList[count++] = summery.getKey();
    }
    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest( bucketName ).withKeys( keysList );
    this.s3client.deleteObjects(deleteObjectsRequest);
}

你可以试试这个

void deleteS3Folder(String bucketName, String folderPath) {
    for (S3ObjectSummary file : s3.listObjects(bucketName, folderPath).getObjectSummaries()){
        s3.deleteObject(bucketName, file.getKey());
    }
}

您可以试试下面的方法,即使是截断的页面,它也会处理删除,并且会递归删除给定目录中的所有内容:

   public Set<String> listS3DirFiles(String bucket, String dirPrefix) {
        ListObjectsV2Request s3FileReq = new ListObjectsV2Request()
                .withBucketName(bucket)
                .withPrefix(dirPrefix)
                .withDelimiter("/");

        Set<String> filesList = new HashSet<>();
        ListObjectsV2Result objectsListing;
        try {
            do {
                objectsListing = amazonS3.listObjectsV2(s3FileReq);
                objectsListing.getCommonPrefixes().forEach(folderPrefix -> {
                    filesList.add(folderPrefix);
                    Set<String> tempPrefix = listS3DirFiles(bucket, folderPrefix);
                    filesList.addAll(tempPrefix);
                });

                for (S3ObjectSummary summary: objectsListing.getObjectSummaries()) {
                    filesList.add(summary.getKey());
                }

                s3FileReq.setContinuationToken(objectsListing.getNextContinuationToken());
            } while(objectsListing.isTruncated());
        } catch (SdkClientException e) {
            System.out.println(e.getMessage());
            throw e;
        }

        return filesList;
    }

    public boolean deleteDirectoryContents(String bucket, String directoryPrefix) {
        Set<String> keysSet = listS3DirFiles(bucket, directoryPrefix);

        if (keysSet.isEmpty()) {
            System.out.println("Given directory {} doesn't have any file "+ directoryPrefix);
            return false;
        }

        DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket)
                .withKeys(keysSet.toArray(new String[0]));
        try {
            amazonS3.deleteObjects(deleteObjectsRequest);
        }  catch (SdkClientException e) {
            System.out.println(e.getMessage());
            throw e;
        }

        return true;
    }