如何复制bucketName / folder1 / folder2形式的存储桶内容

时间:2014-10-06 17:12:01

标签: java amazon-s3

我想复制folder2内容而不是bucketName的全部内容。我使用以下代码但没有成功。我实际上看不到输出。如果我只是复制存储桶的内容而不是子文件夹,我会在目标存储桶中看到整个内容。如何在存储桶下复制子文件夹2的内容。

 System.out.println("Listing objects and copying objects");
        if (!prefix.endsWith(delimiter)) {
            prefix += delimiter;
        }
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
            .withBucketName(bucketName)
            .withPrefix(prefix)
            .withDelimiter(delimiter);
        ObjectListing objectListing;            
            objectListing = s3Client.listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : 
                objectListing.getObjectSummaries()) { s3Client.copyObject(bucketName, objectSummary.getKey(), bucketName2,  "output/" + objectSummary.getKey());
                System.out.println(" - " + objectSummary.getKey() + "  " +
                        "(size = " + objectSummary.getSize() + 
                        ")");
            listObjectsRequest.setMarker(objectListing.getNextMarker());

1 个答案:

答案 0 :(得分:0)

我设置了一些东西来和你一起试试。我创建了两个桶,一个叫mytestbucket20141006,它作为源,另一个叫mytestbucket20141006b,作为目的地。在源存储桶中,我有一个名为afolder的文件夹,其中包含几个文件。

以下代码已成功将对象复制到目标:

    ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
        .withBucketName("mytestbucket20141006")
        .withPrefix("afolder/afolder2/afolder3");
        //.withDelimiter("/");
    ObjectListing objectListing = s3.listObjects(listObjectsRequest);
    for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
        String key = objectSummary.getKey();
        String newKey = key.replace("afolder/afolder2/afolder3/", "afolder3/");
        s3.copyObject("mytestbucket20141006", key, "mytestbucket20141006b",  newKey);
        System.out.println(key);
    }