Amazon Simple Storage Service
开发人员指南 (API Version 2006-03-01)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。请点击 Amazon AWS 入门,可查看中国地区的具体差异

使用 AWS SDK for Java 复制对象

以下任务将引导您使用 Java 类来复制 Amazon S3 中的对象。

复制对象

1

创建 AmazonS3Client 类的实例。

2

执行 AmazonS3Client.copyObject 方法之一。您需要提供诸如源存储桶名称、源键名称、目标存储桶名称和目标键等请求信息。您可以通过创建 CopyObjectRequest 类的实例来提供此信息,或者选择直接使用 AmazonS3Client.copyObject 方法来提供此信息。

以下 Java 代码示例演示了上述任务。

Copy
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); s3client.copyObject(sourceBucketName, sourceKey, destinationBucketName, destinationKey);

下面的 Java 代码示例将复制对象。使用其他键复制的对象将保存在同一源存储桶中。有关如何创建和测试有效示例的说明,请参阅 测试 Java 代码示例

Copy
import java.io.IOException; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CopyObjectRequest; public class CopyObjectSingleOperation { private static String bucketName = "*** Provide bucket name ***"; private static String key = "*** Provide key *** "; private static String destinationKey = "*** Provide dest. key ***"; public static void main(String[] args) throws IOException { AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); try { // Copying object CopyObjectRequest copyObjRequest = new CopyObjectRequest( bucketName, key, bucketName, destinationKey); System.out.println("Copying object."); s3client.copyObject(copyObjRequest); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, " + "which means your request made it " + "to Amazon S3, but was rejected with an error " + "response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, " + "which means the client encountered " + "an internal error while trying to " + " communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } }