首页 > 解决方案 > 使用java将文件从s3存储桶子文件夹复制到另一个子文件夹时面临重复文件创建问题?

问题描述

使用 java 将文件从 s3 存储桶子文件夹复制到另一个子文件夹时面临创建重复文件的问题。  

我正在尝试使用 java 将文件从 s3 存储桶子文件夹复制到另一个子文件夹。

我的 s3 存储桶名称是test,在test存储桶内我有test123/teast1234包含input.txt文件的子文件夹。路径看起来像:test/test123/test1234/input.txt

我想将 input.txt 文件移动到 

 test/test123/test1234/ test12345/input.txt

我试过下面的代码:

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

但它正在创建如下文件夹结构:  /test/test123/test1234/test123/test1234/ test12345/  重复文件夹结构 

请帮助我。 

标签: javaamazon-web-servicesamazon-s3javers

解决方案


这是您的代码,为清楚起见添加了注释:

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

为什么要将该字符串添加到目标存储桶名称?

正确的代码如下所示:

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

推荐阅读