删除amazon s3 java中的文件,目录和存储桶

时间:2011-10-14 05:01:29

标签: java amazon-web-services

我想知道如何做到这一点。我查看了sdk文档并提供了一些示例,但我很困惑语法通常如何。

如果我想删除文件,我假设我使用deleteObject(path, key)。但是,什么是“关键”?

另外如何删除目录?我似乎无法找到这样做的方法。

9 个答案:

答案 0 :(得分:35)

这段代码适合我。 folderPath类似于“topDir / secondDir /”

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

答案 1 :(得分:13)

S3中的“键”类似于文件路径:

http://bucket.s3.amazonaws.com/some/path/to/use

...位于名为bucket的广告位中,其密钥为some/path/to/use

它实际上并不是一条路径,因为没有文件夹。 S3密钥只是一个大目录(整个存储桶)中文件的文件名。 S3键可以包含/,但除非您设置delimiter argument with listing a bucket,否则它没有特殊含义。

换句话说,拥有一个名为some/object的对象并没有告诉你关于对象some的任何信息(它可能存在也可能不存在 - 两个对象不相关)。

但是,您可以请求具有特定前缀的密钥,因此我可以说“给我所有以some/path/to/开头的密钥,它将返回some/path/to/use。它看起来像”列出目录“,但是它实际上只是要求以特定字符串开头的文件。

我可以很容易地命名这样的事情:

somepathtousea
somepathtouseb

并说“以somepathtouse开头给我一切”(它会说somepathtouseasomepathtouseb)。

注意:S3网址来自several forms

http://s3.amazonaws.com/bucket/key
http://bucket.s3.amazonaws.com/key
http://bucket/key (where bucket is a DNS CNAME record pointing to bucket.s3.amazonaws.com)

编辑:

我查看了the JavaDocs,这是我看到的函数签名(对于AmazonS3Client):

public void deleteObject(java.lang.String bucketName,
                         java.lang.String key)
                  throws AmazonClientException,
                         AmazonServiceException

再次编辑:

现在,文件夹确实存在,作为零长度对象,其内容类型为application/x-directory,关键字以/结尾:

$ AWS_PROFILE=prod aws s3api head-object --bucket example-bucket --key example-directory/
{
    "AcceptRanges": "bytes",
    "LastModified": "Mon, 29 Apr 2019 14:59:36 GMT",
    "ContentLength": 0,
    "ETag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
    "ContentType": "application/x-directory",
    "ServerSideEncryption": "AES256",
    "Metadata": {}
}

这仍然只是惯例,没有什么可以阻止你让文件结束/或文件夹里面的文件不存在。

答案 2 :(得分:5)

您可能需要查看此example,以获取有关如何从S3删除对象的快速参考。

delete的语法实际上是 deleteObject( bucketName, key ) 其中bucketName是放置文件的存储桶,key是要在存储桶中删除的文件的名称。

将存储桶视为您的硬盘驱动器,如C:\,D:\等。并将键作为要删除的文件的绝对路径名。

答案 3 :(得分:3)

/ *这是适用于我的解决方案。这里Bucket_Name是我在S3上的桶名,key是Bucket_Name下的路径。所以,如果S3上的绝对路径是:

S3:// MY_BUCKET /路径/到/我/文件夹

然后,下面的代码应该有效。 * /

    String Bucket_Name = "my_bucket";
    String key = "Path/to/my/folder";   
    ObjectListing objects = s3Client.listObjects(BUCKET_NAME, key);
        for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) 
            {
            s3Client.deleteObject(BUCKET_NAME, objectSummary.getKey());
            }           

答案 4 :(得分:2)

适合我,谨防截断!

    long start = System.currentTimeMillis();
    long totalSize = 0;
    int totalItems = 0;

    String key ="path/to/folder/"
    String bucket = "my-bucket"

    final ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName).withPrefix(key);

    ObjectListing objects = s3.listObjects(listObjectsRequest);
    do {
        for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
            totalSize += objectSummary.getSize();
            totalItems++;
            s3.deleteObject(bucketName, objectSummary.getKey());
        }
        objects = s3.listNextBatchOfObjects(objects);
    } while (objects.isTruncated());

    long stop = System.currentTimeMillis();

    LOG.trace("User {} had {} items with {} Kb, took {} ms to delete", user.getName(), totalItems, totalSize / 1024, stop
            - start);

答案 5 :(得分:1)

ListObjectsV2Result为我工作。试一次。

private void deleteObjectsInFolder() {
    try {
        ListObjectsV2Result result;
        do {
            String folderPath =   " ";



            result = s3.listObjectsV2(Constants.BUCKET_NAME, folderPath);

            Log.e("count:", result.getKeyCount() + "");

            if (result.getKeyCount() != 0) {

                for (S3ObjectSummary objectSummary :
                        result.getObjectSummaries()) {
                    s3.deleteObject(Constants.BUCKET_NAME, objectSummary.getKey());
                }

            }


            System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
        } while (result.isTruncated() == true);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, " +
                "which means your request made it " +
                "to Amazon S3, but was rejected with an error response " +
                "for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, " +
                "which means the client encountered " +
                "an internal error while trying to communicate" +
                " with S3, " +
                "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

答案 6 :(得分:1)

按批量删除S3存储桶中的对象列表:

public void deleteObjects(String bucketName, List<String> keys) {

    List<KeyVersion> bulk = new ArrayList<>();
    for (int i = 0; i < keys.size(); i++) {
        bulk.add(new KeyVersion(keys.get(i)));
        if (i % 100 == 0) {
            try {
                s3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bulk));
            } catch (Exception e) {
                System.err.println(e.getErrorMessage());
            }
            bulk.clear();
        }
    }
    if (bulk.size() > 0) {
        try {
            s3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bulk));
        } catch (Exception e) {
            System.err.println(e.getErrorMessage());
        }
    }
}

来源:http://codeflex.co/delete-objects-from-amazon-s3-bucket-using-aws-sdk-for-java/

答案 7 :(得分:0)

由于质疑在亚马逊S3 java中删除文件,目录和存储桶,我想提供删除非空S3存储桶(AWS Reference)的代码:

 public void deleteBucket(final String bucketName) {

        final AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();

        try {
            ObjectListing objectListing = s3.listObjects(bucketName);
            while (true) {
                for (Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator.hasNext(); ) {
                    S3ObjectSummary summary = (S3ObjectSummary) iterator.next();
                    s3.deleteObject(bucketName, summary.getKey());
                }

                if (objectListing.isTruncated()) {
                    objectListing = s3.listNextBatchOfObjects(objectListing);
                } else {
                    break;
                }
            }

            VersionListing versionListing = s3.listVersions(new ListVersionsRequest().withBucketName(bucketName));
            while (true) {
                for (Iterator<?> iterator = versionListing.getVersionSummaries().iterator(); iterator.hasNext(); ) {
                    S3VersionSummary vs = (S3VersionSummary) iterator.next();
                    s3.deleteVersion(bucketName, vs.getKey(), vs.getVersionId());
                }

                if (versionListing.isTruncated()) {
                    versionListing = s3.listNextBatchOfVersions(versionListing);
                } else {
                    break;
                }
            }

            s3.deleteBucket(bucketName);
        } catch (AmazonServiceException e) {
            System.err.println(e.getErrorMessage());
        }
    }

答案 8 :(得分:0)

在我的情况下,此行代码适用于keyName是文件名:

s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));