首页 > 解决方案 > 如何将文件从一个 S3 客户端移动到另一个 S3 客户端

问题描述

如果我有两个 aws 服务帐户,每个帐户都可以访问 s3 存储桶(两者都无法访问)。有没有一种有效的方法在每个桶之间发送文件?

这是我到目前为止所拥有的:

System.setProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "true");

//first account client
AWSCredentials credentialsFrom = new BasicAWSCredentials(fromAccessKey, fromSecretKey);
AmazonS3 s3ClientFrom = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentialsFrom)).withRegion(Regions.US_EAST_1).build();

//second account client
AWSCredentials credentialsTo = new BasicAWSCredentials(toAccessKey, toSecretKey);
AmazonS3 s3ClientTo = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentialsTo)).withRegion(Regions.US_EAST_1).build();

//get contents from first s3 client
ListObjectsRequest listObjectsRequestFrom = new ListObjectsRequest().withBucketName(fromBucket).withPrefix(fromPrefix).withDelimiter("/");
ObjectListing listingFrom = s3ClientFrom.listObjects(listObjectsRequestFrom);

//get each file from first s3 client
for (S3ObjectSummary objectSummary: listingFrom.getObjectSummaries()) {
    S3Object s3Object = s3ClientFrom.getObject(new GetObjectRequest(fromBucket, objectSummary.getKey()));
    //if current key is not a directory
    if(!objectSummary.getKey().substring(objectSummary.getKey().length() - 1).equalsIgnoreCase("/")) {
        //get name of the file by splitting the key/path by "/"
        String[] fileName = objectSummary.getKey().split("[/]");

        //put current file contents to new bucket
        s3ClientTo.putObject(toBucket, toPrefix + fileName[fileName.length - 1], s3Object.getObjectContent(), s3Object.getObjectMetadata());
    }
}

标签: javaamazon-s3

解决方案


Seems like the code snippet in the question is the correct way to do it. I'll update the answer if anyone else has a better/cleaner solution. Thank you xerx593 for your help!


推荐阅读