简体   繁体   中英

How do I copy contents of a bucket which is of the form bucketName/folder1/folder2

I want to copy folder2 contents and not the whole contents of bucketName. I am using the following code but no success. I actually see no output. If I just copy the contents of the bucket and not the sub folders, I see the entire contents in the destination bucket. How do I just copy the contents of the subfolder2 under the bucket.

 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());

I set up something to try this out with you. I created two buckets, one called mytestbucket20141006, which acts as the source, and another one called mytestbucket20141006b, acts as destination. Inside the source bucket, I have a folder called afolder, which contains couple files.

The following code successfully copied objects to the destination:

    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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM