[ 云计算 | AWS 实践 ] Java 如何重命名 Amazon S3 中的文件和文件夹
在Amazon S3中,重命名对象(文件或文件夹)可以通过复制对象后再删除原对象的方式实现。以下是使用Java AWS SDK进行操作的示例代码:
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
public class S3RenameExample {
public static void main(String[] args) {
// 初始化AWS凭证
AWSCredentials credentials = new BasicAWSCredentials("your-access-key-id", "your-secret-access-key");
// 创建S3客户端
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(Regions.DEFAULT_REGION) // 替换为你的S3区域
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
// 设置源对象和目标对象的位置
String bucketName = "your-bucket-name";
String oldKey = "old-folder-or-file-path/old-name";
String newKey = "old-folder-or-file-path/new-name";
// 复制对象
s3Client.copyObject(new CopyObjectRequest(bucketName, oldKey, bucketName, newKey));
// 删除原对象
s3Client.deleteObject(new DeleteObjectRequest(bucketName, oldKey));
}
}
确保替换your-access-key-id
, your-secret-access-key
, your-bucket-name
, old-folder-or-file-path/old-name
, 和 old-folder-or-file-path/new-name
为你的AWS凭证、桶名、原始对象路径和新对象路径。
请注意,这个操作不会更新S3内的任何文件夹引用,如果文件夹中有内容,重命名后旧的文件夹路径将变为不可访问。如果需要更新文件夹引用,可能需要更复杂的逻辑来重命名包含内容的文件夹。
评论已关闭