すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:OSS SDK の使用開始

最終更新日:Feb 17, 2025

OSS SDK を使用すると、バケットの作成、オブジェクトのアップロード、オブジェクトのダウンロードなどの操作を実行できます。このトピックでは、OSS SDK for Java を例として使用して、OSS でプログラムによって操作を実行する方法を示します。

前提条件

バケットの作成

バケットは、OSS のグローバル名前空間です。バケットは、オブジェクトを格納するために使用されるコンテナーです。次のサンプルコードは、バケットを作成する方法の例を示しています。

サンプルコードが正常に実行されると、examplebucket バケットが作成されます。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;

public class Demo {

    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。名前は OSS で一意である必要があります。
        String bucketName = "examplebucket";

        // OSSClient インスタンスを作成します。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // バケットを作成します。
            ossClient.createBucket(bucketName);

        } 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 (ClientException 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();
            }
        }
    }
}

オブジェクトのアップロード

次のサンプルコードは、ストリーミングアップロードを使用してオブジェクトを OSS にアップロードする方法の例を示しています。

サンプルコードが正常に実行されると、exampleobject.txt オブジェクトが exampledir ディレクトリにアップロードされます。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import java.io.ByteArrayInputStream;

public class Demo {

    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";

        // OSSClient インスタンスを作成します。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            String content = "Hello OSS";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
        } 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 (ClientException 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();
            }
        }
    }
}

オブジェクトのダウンロード

次のサンプルコードは、ストリーミングダウンロードを使用して OSS からオブジェクトをダウンロードする方法の例を示しています。

サンプルコードが正常に実行されると、ダウンロードされたオブジェクトの内容がコンパイラに表示されます。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.OSSObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Demo {

    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";

        // OSSClient インスタンスを作成します。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // ossClient.getObject を呼び出して、OSSObject インスタンスを取得します。OSSObject インスタンスには、オブジェクトのコンテンツとメタデータが含まれています。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // ossObject.getObjectContent を呼び出して、オブジェクトの入力ストリームを取得します。入力ストリームを読み取って、オブジェクトのコンテンツを取得できます。
            InputStream content = ossObject.getObjectContent();
            if (content != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                      break;
                    }
                    System.out.println("\n" + line);
                }
                // オブジェクトの読み取り後、取得したストリームを閉じる必要があります。そうしないと、接続リークが発生する可能性があります。その結果、接続が使用できなくなり、例外が発生します。
                content.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 (ClientException 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();
            }
        }
    }
}

オブジェクトのリスト

次のサンプルコードは、バケット内のオブジェクトをリストする方法の例を示しています。デフォルトでは、最大 100 個のオブジェクトがリストされます。

サンプルコードが正常に実行されると、exampledir/exampleobject.txt オブジェクトの詳細がコンパイラに表示されます。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;

public class Demo {

    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";

        // OSSClient インスタンスを作成します。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // ossClient.listObjects を呼び出して、ObjectListing インスタンスを取得します。ObjectListing インスタンスには、listObject リクエストへの応答が含まれています。
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            // objectListing.getObjectSummaries を呼び出して、すべてのオブジェクトの説明を取得します。
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + "  " +
                        "(size = " + objectSummary.getSize() + ")");
            }
        } 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 (ClientException 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 オブジェクトが exampledir ディレクトリから削除されます。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;

public class Demo {

    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";

        // OSSClient インスタンスを作成します。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // オブジェクトを削除します。
            ossClient.deleteObject(bucketName, objectName);
        } 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 (ClientException 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();
            }
        }
    }
}

関連情報

他のプログラミング言語の OSS SDK を使用して、バケットの作成、オブジェクトのアップロード、オブジェクトのダウンロードなどの操作を実行する方法の詳細については、以下のトピックをご参照ください。