サイズの大きいファイルを処理したり、データを増分処理したりする場合、ストリーミングダウンロードを使用して、OSS からファイルの内容をチャンク単位で読み取ることができます。このメソッドは、ファイル全体を一度にメモリにロードすることを回避し、プログラムの効率とパフォーマンスを向上させます。このメソッドは、メモリ制限を超えるファイルのダウンロード、メモリ使用量を削減するためのリアルタイムでのデータ処理、およびネットワーク経由での段階的なデータ取得に適しています。
注意事項
このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。同じリージョン内の他の Alibaba Cloud サービスから OSS にアクセスするには、内部エンドポイントを使用します。サポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。
このトピックでは、環境変数からアクセス認証情報を取得します。アクセス認証情報の設定方法の詳細については、「アクセス認証情報の設定」をご参照ください。
このトピックでは、OSS エンドポイントを使用して OSSClient インスタンスを作成します。カスタムドメイン名またはセキュリティトークンサービス (STS) を使用して OSSClient インスタンスを作成する場合は、「一般的なシナリオの設定例」をご参照ください。
ストリーミングダウンロードを実行するには、
oss:GetObject権限が必要です。詳細については、「RAM ユーザーへのカスタムポリシーのアタッチ」をご参照ください。
サンプルコード
次のサンプルコードは、OSS からファイルの内容をチャンク単位で読み取り、その内容をバイト配列に格納します。
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class Stream {
public static void main(String[] args) throws Exception {
// 中国 (杭州) リージョンのエンドポイントを例として使用します。実際のエンドポイントに置き換えてください。他のリージョンのエンドポイントの詳細については、「アクセスドメイン名とデータセンター」をご参照ください。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケット名を指定します。例:examplebucket。
String bucketName = "examplebucket";
// オブジェクトの完全なパスを指定します。例:exampledir/exampleobject.txt。完全なパスにバケット名を含めることはできません。
String objectName = "exampledir/exampleobject.txt";
// バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、リージョンを cn-hangzhou に設定します。
String region = "cn-hangzhou";
// OSSClient インスタンスを作成します。
// OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// ossObject には、バケット名、オブジェクト名、オブジェクトのメタデータ、および入力ストリームが含まれます。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
InputStream inputStream = ossObject.getObjectContent();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// ファイルの内容をバイト配列に読み込みます。
byte[] readBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(readBuffer)) != -1) {
byteArrayOutputStream.write(readBuffer, 0, bytesRead);
}
// 最終的なバイト配列を取得します。
byte[] fileBytes = byteArrayOutputStream.toByteArray();
// バイト配列の長さを出力します。
System.out.println("Downloaded file size: " + fileBytes.length + " bytes");
// データの読み取り後、ストリームを閉じます。そうしないと、接続リークが発生し、利用可能な接続を使い果たしてプログラムが失敗する可能性があります。
inputStream.close();
byteArrayOutputStream.close();
// ossObject の使用が終了したら、閉じる必要があります。そうしないと、接続リークが発生し、利用可能な接続を使い果たしてプログラムが失敗する可能性があります。
ossObject.close();
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Throwable ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}次のコードは、exampleobject.txt ファイルのストリーミングデータをローカルの D:\localpath ディレクトリにある examplefile.txt にダウンロードします。
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import java.io.*;
public class GetObjectStreamtoLocalFile {
public static void main(String[] args) throws Exception {
// 中国 (杭州) リージョンのエンドポイントを例として使用します。実際のエンドポイントに置き換えてください。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数からアクセス認証情報を取得します。
EnvironmentVariableCredentialsProvider credentialsProvider =
CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケット名を指定します。例:examplebucket。
String bucketName = "examplebucket";
// オブジェクトの完全なパスを指定します。例:exampledir/exampleobject.txt。
String objectName = "exampledir/exampleobject.txt";
// バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、リージョンを cn-hangzhou に設定します。
String region = "cn-hangzhou";
// 保存用のローカルファイルパスを指定します。
String localFilePath = "D:\\localpath\\examplefile.txt"; // これを実際のローカルファイルパスに置き換えてください。
// OSSClient インスタンスを作成します。
// OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// OSS オブジェクトの入力ストリームを取得します。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
InputStream inputStream = ossObject.getObjectContent();
// ローカルの出力ストリームを作成します。
try (FileOutputStream fileOutputStream = new FileOutputStream(localFilePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
// チャンク単位で読み取り、ローカルファイルに書き込みます。
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
System.out.println("Downloaded file saved to: " + localFilePath);
}
// 入力ストリームを閉じます。
inputStream.close();
// OSSObject を閉じます。
ossObject.close();
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Throwable ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}