Download objects (Java SDK V2)
Download 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-v2to your pom.xml.Access credentials are configured by using environment variables. The sample code in this topic uses
EnvironmentVariableCredentialsProviderto read credentials from theOSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables.
Permissions
An Alibaba Cloud account has full permissions by default. RAM users and RAM roles under the account have no permissions by default. The Alibaba Cloud account or an account administrator must grant the required permissions before the RAM user or role can perform the operations.
API | Action | Description |
GetObject |
| Downloads 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.*;
import com.aliyun.sdk.service.oss2.utils.IOUtils;
public class VersioningGetObjectSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String bucket = "examplebucket";
String key = "exampleobject";
String versionId = "CAEQNhiBgM0BYiIDc4MGZj****";
CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
OSSClientBuilder clientBuilder = OSSClient.newBuilder()
.credentialsProvider(provider)
.region(region);
try (OSSClient client = clientBuilder.build()) {
// Download the object with the specified version ID
try (GetObjectResult result = client.getObject(GetObjectRequest.newBuilder()
.bucket(bucket)
.key(key)
.versionId(versionId)
.build())) {
byte[] data = IOUtils.toByteArray(result.body());
System.out.printf("status code:%d, request id:%s, version id:%s%n",
result.statusCode(), result.requestId(), result.versionId());
System.out.printf("content length:%d%n", result.contentLength());
}
} catch (Exception e) {
System.out.printf("error:%n%s", e);
}
}
}
References
For the synchronous sample code, see GetObject.java.
For the asynchronous sample code, see GetObjectAsync.java.