Copy objects (Java SDK V2)

Updated at:

Copy a previous version of an object from a versioning-enabled bucket by specifying the version ID with OSS Java SDK V2.

Prerequisites

  • OSS Java SDK V2 is installed. If you use Maven, add the dependency com.aliyun:alibabacloud-oss-v2 to your pom.xml file.

  • Access credentials are configured by using environment variables. The sample code in this topic uses EnvironmentVariableCredentialsProvider to read credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

Permissions

By default, an Alibaba Cloud account has full permissions on its resources. RAM users and RAM roles under the account have no permissions by default. The Alibaba Cloud account owner or an account administrator must grant the required permissions.

API

Action

Description

CopyObject

oss:GetObject

Copies the specified version of an object by version ID.

Sample code

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.*;

public class VersioningCopyObjectSample {
    public static void main(String[] args) throws Exception {
        String region = "cn-hangzhou";
        String sourceBucket = "sourcebucket";
        String sourceKey = "sourceobject";
        String sourceVersionId = "CAEQNhiBgM0BYiIDc4MGZj****";
        String bucket = "destbucket";
        String key = "destobject";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {

            // Copy the source object with the specified version ID
            CopyObjectResult result = client.copyObject(CopyObjectRequest.newBuilder()
                    .bucket(bucket)
                    .key(key)
                    .sourceBucket(sourceBucket)
                    .sourceKey(sourceKey)
                    .sourceVersionId(sourceVersionId)
                    .build());

            System.out.printf("status code:%d, request id:%s%n",
                    result.statusCode(), result.requestId());
            System.out.printf("new version id:%s%n", result.versionId());

        } catch (Exception e) {
            System.out.printf("error:%n%s", e);
        }
    }
}

References