1

Facing problem with duplicate file creation while copying file from s3 bucket  subfolder to another sub folder using java.  

I am trying to copy file from s3 bucket sub folder to another sub folder using java.

My s3 bucket name is test and inside test bucket I have sub folders test123/teast1234 which contains input.txt file.  path looks like :test/test123/test1234/input.txt

I want to move input.txt file to 

 test/test123/test1234/ test12345/input.txt

I have tried below code :

s3client.copyObject(bucketName, objectKey, bucketName + "/test/test123/test1234/ test12345/", objectKey);
s3client.deleteObject(bucketName, objectKey);

but it is creating folder structure like below:  /test/test123/test1234/test123/test1234/ test12345/  duplicate folder structure 

please help me on this. 

RKC
  • 17
  • 2
  • 8

1 Answers1

0

This is your code, with comments added for clarity:

s3client.copyObject(
    bucketName,     // Source bucket name
    objectKey,      // Source key
    bucketName + "/test/test123/test1234/ test12345/", // Destination bucket name
    objectKey       // Destination key
);

Why are you adding that string to the destination bucket name?

The correct code would look something like the following:

String bucketName     = "test";
String objectKey      = "/test123/test1234/input.txt";
String destinationKey = "/test123/test1234/test12345/input.txt";

// Copy the object to the new path
s3client.copyObject(
    bucketName,     // Source bucket name
    objectKey,      // Source key
    bucketName,     // Destination bucket name
    destinationKey  // Destination key
);

// Delete the object at the old path
s3client.deleteObject(bucketName, objectKey);
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • Hi mark ,thanks for quick reply,but i want to copy file to same directory level, by creating new folder and removing from old path.i.e /test123/test1234/input.txt to /test123/test1234/test12345/input.txt – RKC Jan 10 '20 at 14:03
  • First, just change `destinationKey` to whatever you want the final folder/filename to be. I believe I've updated my code above to what you need. Second, S3 has no "move" or "rename" functionality. So if you are trying to move an object to a different location you will need to perform a `deleteObject` operation on the old object. See my edits above. – Mark B Jan 10 '20 at 14:11