大容量のオブジェクトをダウンローズする場合、またはオブジェクト全体を一度にダウンロードするのに時間がかかる場合は、ストリーミングダウンロードを使用します。 ストリーミングダウンロードでは、オブジェクト全体をダウンロードし終わるまで、オブジェクトのパーツをその都度ダウンロードし続けます。
使用後に OssObject を終了しない場合、接続リークが発生する可能性があります。 その結果、利用可能な接続がなくなり、プログラムを正しく実行できません。 次のコードを実行し、OssObject を終了します。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
ossObject.close();
以下のコードはストリーミングダウンロードに使用されます。
// This example uses the endpoint China East 1 (Hangzhou). Specify the actual endpoint based on your requirements.
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// It is highly risky to log on with AccessKey of an Alibaba Cloud account because the account has permissions on all the APIs in OSS. We recommend that you log on as a RAM user to access APIs or perform routine operations and maintenance. To create a RAM account, log on to https://ram.console.aliyun.com.
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>";
// Create an OSSClient instance.
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// ossObject includes the bucket name, key (object name), object meta (meta information), and InputStream.
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
// Read the object content.
System.out.println("Object content:");
BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println("\n" + line);
}
// If you do not close the reader after the data is read, connection leaks may occur. Consequently, no connection is available and the program cannot run properly.
reader.close();
//Close your OSSClient.
ossClient.shutdown();
ストリーミングダウンロードの完全なコードについては、『GitHub』をご参照ください。