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

Object Storage Service:OSS SDK for Javaを使用したオブジェクトのリスト

最終更新日:Oct 30, 2024

このトピックでは、すべてのオブジェクト、特定の数のオブジェクト、および名前に特定のプレフィックスが含まれるオブジェクトをObject Storage Service (OSS) バケットに一覧表示する方法について説明します。

使用上の注意

  • このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 OSSと同じリージョンにある他のAlibaba CloudサービスからOSSにアクセスする場合は、内部エンドポイントを使用します。 OSSリージョンとエンドポイントの詳細については、「リージョン、エンドポイント、オープンポート」をご参照ください。

  • このトピックでは、アクセス資格情報は環境変数から取得します。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。

  • このトピックでは、OSSエンドポイントを使用してOSSClientインスタンスを作成します。 カスタムドメイン名またはSecurity Token Service (STS) を使用してOSSClientインスタンスを作成する場合は、「OSSClientインスタンスの作成」をご参照ください。

  • オブジェクトを一覧表示するには、oss:ListObjects権限が必要です。 詳細については、「RAMユーザーへのカスタムポリシーのアタッチ」をご参照ください。

背景情報

GetBucket (ListObjects) またはGetBucketV2 (ListObjectsV2) 操作を呼び出して、一度に最大1,000個のオブジェクトをバケットに一覧表示できます。 リスト操作パラメーターを指定して、ビジネス要件に基づいてオブジェクトを一覧表示できます。 たとえば、特定の位置の後にすべてのオブジェクトを一覧表示したり、特定のディレクトリ内のすべてのオブジェクトとサブディレクトリを一覧表示したり、ページごとに1,000を超えるオブジェクトを一覧表示したりできます。 GetBucket (ListObjects) 操作とGetBucketV2 (ListObjectsV2) 操作にはいくつかの違いがあります。

  • GetBucket (ListObjects) 操作を呼び出してオブジェクトを一覧表示すると、オブジェクト所有者情報が応答に含まれます。

  • GetBucketV2 (ListObjectsV2) 操作を呼び出してオブジェクトを一覧表示する場合、fetchOwnerパラメーターを設定して、応答にオブジェクト所有者情報を含めるかどうかを指定できます。

    説明

    バージョン管理が有効なバケット内のオブジェクトを一覧表示するには、GetBucketV2 (ListObjectsV2) 操作を呼び出すことを推奨します。

次の表では、GetBucket (ListObjects) またはGetBucketV2 (ListObjectsV2) 操作を呼び出してオブジェクトを一覧表示するときに設定できるパラメーターについて説明します。

  • GetBucket (ListObjects)

    GetBucket (ListObjects) 操作は、次のいずれかの形式で呼び出すことができます。

    • ObjectListing listObjects(String bucketName): バケット内のすべてのオブジェクトを一覧表示します。 デフォルトでは、1つのリクエストに最大100個のオブジェクトを一覧表示できます。

    • ObjectListing listObjects(String bucketName, String prefix): バケット内の特定のプレフィックスを名前に含むオブジェクトを一覧表示します。 デフォルトでは、1回のリクエストで最大100個のオブジェクトを一覧表示できます。

    • ObjectListing listObjects(ListObjectsRequest listObjectsRequest): 指定された条件を満たすオブジェクトを一覧表示します。 この形式を使用して、オブジェクトを柔軟に一覧表示できます。

    次の表に、GetBucket (ListObjects) 操作を呼び出すときに指定できるパラメーターを示します。

    パラメーター

    説明

    移動方法

    objectSummaries

    一覧表示するオブジェクトのメタデータ。

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    一覧表示するオブジェクトの名前のプレフィックス。

    String getPrefix()

    delimiter

    リストするオブジェクトを名前でグループ化するために使用される文字。

    String getDelimiter()

    marker

    リスト操作の開始位置。

    String getMarker()

    maxKeys

    一度に一覧表示できるオブジェクトの最大数。

    int getMaxKeys()

    nextMarker

    次のリスト操作が開始される位置。

    String getNextMarker()

    isTruncated

    オブジェクトリストを切り捨てるかどうかを指定します。 有効な値:

    • false: すべてのオブジェクトは切り捨てなしでリストされます。

    • true: オブジェクトの一部のみがリストされます。

    boolean isTruncated()

    commonPrefixes

    オブジェクト名の部分文字列のセット。 名前が区切り文字で終わり、同じプレフィックスを含むオブジェクトは、CommonPrefixesで単一の結果要素としてグループ化されます。

    List<String> getCommonPrefixes()

    encodingType

    レスポンス内のオブジェクト名のエンコードタイプ。

    String getEncodingType()

  • GetBucketV2 (ListObjectsV2)

    GetBucketV2 (ListObjectsV2) 操作は、次のいずれかの形式で呼び出すことができます。

    • ListObjectsV2Result listObjectsV2(String bucketName): バケット内のすべてのオブジェクトを一覧表示します。 デフォルトでは、1回のリクエストで最大100個のオブジェクトを一覧表示できます。

    • ListObjectsV2Result listObjectsV2(String bucketName, String prefix): バケット内の特定のプレフィックスを名前に含むオブジェクトを一覧表示します。 デフォルトでは、1回のリクエストで最大100個のオブジェクトを一覧表示できます。

    • ListObjectsV2Result listObjectsV2(ListObjectsRequest listObjectsRequest): 指定された条件を満たすオブジェクトを一覧表示します。 この形式を使用して、オブジェクトを柔軟に一覧表示できます。

    次の表に、GetBucketV2 (ListObjectsV2) 操作を呼び出すときに指定できるパラメーターを示します。

    パラメーター

    説明

    移動方法

    objectSummaries

    一覧表示するオブジェクトのメタデータ。

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    一覧表示するオブジェクトの名前のプレフィックス。

    String getPrefix()

    delimiter

    リストするオブジェクトを名前でグループ化するために使用される文字。

    String getDelimiter()

    startAfter

    リスト操作の開始位置。

    文字列getStartAfter()

    maxKeys

    一度に一覧表示できるオブジェクトの最大数。

    int getMaxKeys()

    continuationToken

    リスト操作の開始位置。

    文字列getContinuationToken()

    nextContinuationToken

    次のリスト操作が開始される位置。

    文字列getNextContinuationToken()

    isTruncated

    オブジェクトリストを切り捨てるかどうかを指定します。 有効な値:

    • false: すべてのオブジェクトは切り捨てなしでリストされます。

    • true: オブジェクトの一部のみがリストされます。

    boolean isTruncated()

    commonPrefixes

    オブジェクト名の部分文字列のセット。 名前が区切り文字で終わり、同じプレフィックスを含むオブジェクトは、CommonPrefixesで単一の結果要素としてグループ化されます。

    List<String> getCommonPrefixes()

    encodingType

    レスポンス内のオブジェクト名のエンコードタイプ。

    String getEncodingType()

    fetchOwner

    レスポンスにオブジェクト所有者情報を含めるかどうかを指定します。 有効な値:

    • true: 応答にはオブジェクト所有者情報が含まれます。

    • false: レスポンスにオブジェクト所有者情報が含まれていません。

    文字列getFetchOwner()

単純なリストを使用してオブジェクトをリストする

GetBucket (ListObjects) 操作またはGetBucketV2 (ListObjectsV2) 操作を呼び出して、特定のバケット内のオブジェクトを一覧表示できます。

GetBucket (ListObjects) 操作を呼び出してオブジェクトを一覧表示する

次のサンプルコードでは、GetBucket (ListObjects) 操作を呼び出して、特定のバケット内のオブジェクトを一覧表示する方法の例を示します。 デフォルトでは、100のオブジェクトがリクエストに一覧表示されます。

import com.aliyun.oss.ClientException;
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.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects. If you do not specify keyPrefix, all objects in the bucket are listed. If you specify keyPrefix, the objects whose names contain the specified prefix are listed. 
            ObjectListing objectListing = ossClient.listObjects(bucketName, keyPrefix);
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}                  

GetBucketV2 (ListObjectsV2) 操作を呼び出してオブジェクトを一覧表示する

次のサンプルコードでは、GetBucketV2 (ListObjectsV2) 操作を呼び出して、特定のバケット内のオブジェクトを一覧表示する方法の例を示します。 デフォルトでは、100のオブジェクトはリクエストによって一覧表示されます。

import com.aliyun.oss.ClientException;
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.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects. If you do not specify keyPrefix, all objects in the bucket are listed. If you specify keyPrefix, the objects whose names contain the specified prefix are listed. 
            ListObjectsV2Result result = ossClient.listObjectsV2(bucketName, keyPrefix);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

            for (OSSObjectSummary s : ossObjectSummaries) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}

ListObjectsRequest操作を呼び出してオブジェクトを一覧表示する

ListObjectsRequest操作を呼び出して、オブジェクトを柔軟に一覧表示するときにパラメーターを指定できます。 次の表に、ListObjectsRequest操作を呼び出すときに指定できるパラメーターを示します。

パラメーター

説明

移動方法

prefix

一覧表示するオブジェクトの名前に含める必要があるプレフィックス。

setPrefix(String prefix)

delimiter

リストするオブジェクトを名前でグループ化するために使用される文字。 たとえば、区切り文字をスラッシュ (/) に設定できます。 指定されたプレフィックスからスラッシュ (/) の最初の出現までの同じ文字列を名前に含むオブジェクトは、CommonPrefixes要素としてグループ化されます。 名前がCommonPrefixes要素を含むすべてのオブジェクトがリストされます。 区切り文字パラメーターを使用して、オブジェクトを階層的に管理およびクエリできます。 これにより、より整理された直感的なクエリ結果が得られます。

setDelimiter(String delimiter)

marker

リスト操作の開始位置。 markerの値の後にアルファベット順に名前が付いているオブジェクトが一覧表示されます。

setMarker(String marker)

maxKeys

一度に一覧表示できるオブジェクトの最大数。 このパラメーターを指定すると、オブジェクトはアルファベット順に一覧表示されます。 最大値は 1000 です。 デフォルト値:100

setMaxKeys(Integer maxKeys)

encodingType

レスポンス内のオブジェクト名のエンコードタイプ。 有効値: URL。

setEncodingType(String encodingType)

特定の数のオブジェクトを一覧表示する

次のサンプルコードは、バケット内の特定の数のオブジェクトを一覧表示する方法の例を示しています。

import com.aliyun.oss.ClientException;
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.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args){
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Specify the maximum number of objects that can be listed at a time. 
            final int maxKeys = 200;
            // List objects. 
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}                    

名前に特定のプレフィックスが含まれるオブジェクトのリスト

次のサンプルコードは、名前に特定のプレフィックスが含まれるオブジェクトをバケットに一覧表示する方法の例を示しています。

import com.aliyun.oss.ClientException;
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.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args){
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects whose names contain the specified prefix. By default, 100 objects are listed. 
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withPrefix(keyPrefix));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}                    

markerの値の後に名前がアルファベット順に表示されるオブジェクトを一覧表示します。

次のサンプルコードは、markerの値の後に名前がアルファベット順になっているオブジェクトを一覧表示する方法の例を示します。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args){
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the name of the object after which the list begins. If this parameter is specified, objects whose names are alphabetically after the value of marker are returned.   
        String marker = "ex";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects whose names are alphabetically after the object specified by marker. By default, 100 objects are listed. 
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(marker));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}

バケット内のすべてのオブジェクトをページごとに一覧表示する

次のサンプルコードでは、バケット内のすべてのオブジェクトをページごとに一覧表示する方法の例を示します。 maxKeysを使用して、各ページに一覧表示できるオブジェクトの最大数を指定できます。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args){
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Set maxKeys to 200. 
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String nextMarker = null;
            ObjectListing objectListing;

            do {
                objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(maxKeys));

                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    System.out.println("\t" + s.getKey());
                }

                nextMarker = objectListing.getNextMarker();

            } while (objectListing.isTruncated());
        } 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();
            }
        }
    }
}

名前に特定のプレフィックスが含まれるオブジェクトをページごとにリストする

次のサンプルコードでは、名前に特定のプレフィックスが含まれているオブジェクトをページごとに一覧表示する方法の例を示します。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args){
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Set maxKeys to 200. 
        int maxKeys = 200;
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // Specify the marker parameter. Example: objecttest.txt. 
        String nextMarker = "objecttest.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ObjectListing objectListing;

            do {
                objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).
                        withPrefix(keyPrefix).withMarker(nextMarker).withMaxKeys(maxKeys));

                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    System.out.println("\t" + s.getKey());
                }

                nextMarker = objectListing.getNextMarker();

            } while (objectListing.isTruncated());

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

特定のエンコーディングタイプを使用して名前がエンコードされているオブジェクトを一覧表示する

オブジェクトの名前に次のいずれかの文字が含まれている場合、オブジェクトを送信する前にオブジェクト名をURLエンコードする必要があります。 OSSはURLエンコードのみをサポートしています。

  • 一重引用符 (')

  • 二重引用符 (")

  • アンパサンド (&)

  • アングルブラケット (<>)

  • 一時停止マーカー (、)

  • 漢字、平仮名、片仮名

次のサンプルコードは、特定のエンコードタイプを使用して名前がエンコードされているオブジェクトを一覧表示する方法の例を示します。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.net.URLDecoder;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Set maxKeys to 200. 
        int maxKeys = 200;
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // Specify the marker parameter. Example: objecttest.txt. 
        String nextMarker = "objecttest.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ObjectListing objectListing;

            do {
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
                listObjectsRequest.setPrefix(keyPrefix);
                listObjectsRequest.setMaxKeys(maxKeys);
                listObjectsRequest.setMarker(nextMarker);

                // Specify the encoding type of the object names. 
                listObjectsRequest.setEncodingType("url");

                objectListing = ossClient.listObjects(listObjectsRequest);

                // Decode the values of object keys in the response. 
                for (OSSObjectSummary objectSummary: objectListing.getObjectSummaries()) {
                    System.out.println("Key:" + URLDecoder.decode(objectSummary.getKey(), "UTF-8"));
                }

                // Decode the value of CommonPrefixes in the response. 
                for (String commonPrefixes: objectListing.getCommonPrefixes()) {
                    System.out.println("CommonPrefixes:" + URLDecoder.decode(commonPrefixes, "UTF-8"));
                }

                // Decode the value of nextMarker in the response. 
                if (objectListing.getNextMarker() != null) {
                    nextMarker = URLDecoder.decode(objectListing.getNextMarker(), "UTF-8");
                }
            } while (objectListing.isTruncated());
        } 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();
            }
        }
    }
}

ListObjectsV2Request操作を呼び出してオブジェクトを一覧表示する

ListObjectsV2Request操作を呼び出して、オブジェクトを柔軟に一覧表示するときにパラメーターを指定できます。 たとえば、特定の数のオブジェクト、名前に特定のプレフィックスが含まれているオブジェクト、またはバケット内のすべてのオブジェクトをページごとにリストできます。

次の表に、ListObjectsV2Request操作を呼び出すときに指定できるパラメーターを示します。

パラメーター

説明

移動方法

prefix

一覧表示するオブジェクトの名前に含める必要があるプレフィックス。

setPrefix(String prefix)

delimiter

リストするオブジェクトを名前でグループ化するために使用される文字。 たとえば、区切り文字をスラッシュ (/) に設定できます。 指定されたプレフィックスからスラッシュ (/) の最初の出現までの同じ文字列を名前に含むオブジェクトは、CommonPrefixes要素としてグループ化されます。 名前がCommonPrefixes要素を含むすべてのオブジェクトがリストされます。 区切り文字パラメーターを使用して、オブジェクトを階層的に管理およびクエリできます。 これにより、より整理された直感的なクエリ結果が得られます。

setDelimiter(String delimiter)

maxKeys

一度に一覧表示できるオブジェクトの最大数。 このパラメーターを指定すると、オブジェクトはアルファベット順に一覧表示されます。 最大値は 1000 です。 デフォルト値:100

setMaxKeys(Integer maxKeys)

startAfter

リスト操作の開始位置。 名前がstartAfterの値の後にアルファベット順にあるオブジェクトがリストされます。

setStartAfter (文字列startAfter)

continuationToken

このリスト操作で使用されるcontinuationToken。

setContinuationToken (文字列continuationToken)

encodingType

レスポンス内のオブジェクト名のエンコードタイプ。 有効値: URL。

setEncodingType(String encodingType)

fetchOwner

応答に所有者情報を含めるかどうかを指定します。

setFetchOwner(boolean fetchOwner)

特定の数のオブジェクトを一覧表示する

次のサンプルコードは、バケット内の特定の数のオブジェクトを一覧表示する方法の例を示しています。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the maximum number of objects that can be listed at a time. 
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects. By default, 100 objects are returned by a single request. In this example, up to 200 objects can be returned at a time. 
            ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
            listObjectsV2Request.setMaxKeys(maxKeys);
            ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

            for (OSSObjectSummary s : ossObjectSummaries) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}

名前に特定のプレフィックスが含まれるオブジェクトのリスト

次のサンプルコードは、名前に特定のプレフィックスが含まれるオブジェクトをバケットに一覧表示する方法の例を示しています。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String prefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects whose names contain the specified prefix. 
            ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
            listObjectsV2Request.setPrefix(prefix);
            ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

            for (OSSObjectSummary s : ossObjectSummaries) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}

startAfterの値の後に名前がアルファベット順であるオブジェクトを一覧表示する

次のサンプルコードは、startAfterの値の後に名前がアルファベット順になっているオブジェクトを一覧表示する方法の例を示しています。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Specify the name of the object after which the list begins. If this parameter is specified, objects whose names are alphabetically after the value of start-after are returned.           
            ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
            listObjectsV2Request.setStartAfter("ex");
            ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

            for (OSSObjectSummary s : ossObjectSummaries) {
                System.out.println("\t" + s.getKey());
            }
        } 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();
            }
        }
    }
}

オブジェクトとその所有者情報の一覧表示

次のサンプルコードは、オブジェクトとその所有者情報を一覧表示する方法の例を示しています。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // By default, the object owner information is not listed. To include the object owner information in the response, set the fetchOwner parameter to true. 
            ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
            listObjectsV2Request.setFetchOwner(true);
            ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

            for (OSSObjectSummary s : ossObjectSummaries) {
                System.out.println("\t" + s.getKey());
                if (s.getOwner() != null) {
                    System.out.println("owner id:" + s.getOwner().getId());
                    System.out.println("name:" + s.getOwner().getDisplayName());
                }
            }
        } 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();
            }
        }
    }
}

バケット内のすべてのオブジェクトをページごとに一覧表示する

次のサンプルコードでは、バケット内のすべてのオブジェクトをページごとに一覧表示する方法の例を示します。 maxKeysを使用して、各ページに一覧表示できるオブジェクトの最大数を指定できます。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the maximum number of objects that can be listed at a time. 
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String nextContinuationToken = null;
            ListObjectsV2Result result = null;

            // List objects by page by using the nextContinuationToken parameter included in the response of the previous list operation. 
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);

                List<OSSObjectSummary> sums = result.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    System.out.println("\t" + s.getKey());
                }

                nextContinuationToken = result.getNextContinuationToken();

            } while (result.isTruncated());
        } 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();
            }
        }
    }
}

名前に特定のプレフィックスが含まれるオブジェクトをページごとにリストする

次のサンプルコードでは、名前に特定のプレフィックスが含まれているオブジェクトをページごとに一覧表示する方法の例を示します。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // Specify the maximum number of objects that can be listed at a time. 
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String nextContinuationToken = null;
            ListObjectsV2Result result = null;

            // List the objects whose names contain the specified prefix by page. 
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setPrefix(keyPrefix);
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);

                List<OSSObjectSummary> sums = result.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    System.out.println("\t" + s.getKey());
                }

                nextContinuationToken = result.getNextContinuationToken();

            } while (result.isTruncated());
        } 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();
            }
        }
    }
}

特定のエンコーディングタイプを使用して名前がエンコードされているオブジェクトを一覧表示する

次のサンプルコードは、特定のエンコードタイプを使用して名前がエンコードされているオブジェクトを一覧表示する方法の例を示します。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.net.URLDecoder;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // Specify the maximum number of objects that can be listed at a time. 
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String nextContinuationToken = null;
            ListObjectsV2Result result = null;

            // Specify that the returned results are URL-encoded. In this case, you must decode the values of the prefix, delimiter, startAfter, key, and commonPrefixes parameters in the response. 
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setPrefix(keyPrefix);
                listObjectsV2Request.setEncodingType("url");
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);

                // Decode the value of prefix in the response. 
                if (result.getPrefix() != null) {
                    String prefix = URLDecoder.decode(result.getPrefix(), "UTF-8");
                    System.out.println("prefix: " + prefix);
                }

                // Decode the value of delimiter in the response. 
                if (result.getDelimiter() != null) {
                    String delimiter = URLDecoder.decode(result.getDelimiter(), "UTF-8");
                    System.out.println("delimiter: " + delimiter);
                }

                // Decode the value of startAfter in the response. 
                if (result.getStartAfter() != null) {
                    String startAfter = URLDecoder.decode(result.getStartAfter(), "UTF-8");
                    System.out.println("startAfter: " + startAfter);
                }

                // Decode the values of object keys in the response. 
                for (OSSObjectSummary s : result.getObjectSummaries()) {
                    String decodedKey = URLDecoder.decode(s.getKey(), "UTF-8");
                    System.out.println("key: " + decodedKey);
                }

                // Decode the value of CommonPrefixes in the response. 
                for (String commonPrefix: result.getCommonPrefixes()) {
                    String decodeCommonPrefix = URLDecoder.decode(commonPrefix, "UTF-8");
                    System.out.println("CommonPrefix:" + decodeCommonPrefix);
                }

                nextContinuationToken = result.getNextContinuationToken();

            } while (result.isTruncated());
        } 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はフラット構造を使用してオブジェクトを格納します。 ディレクトリは、名前がスラッシュ (/) で終わるゼロバイトのオブジェクトです。 このオブジェクトをアップロードおよびダウンロードできます。 デフォルトでは、名前がスラッシュ (/) で終わるオブジェクトは、OSSコンソールにディレクトリとして表示されます。 ディレクトリの作成に使用する完全なサンプルコードについては、『GitHub』をご参照ください。

デリミタとプレフィックスパラメータを指定して、ディレクトリごとにオブジェクトを一覧表示できます。

  • リクエストでプレフィックスをディレクトリ名に設定すると、プレフィックスを含む名前のオブジェクトとサブディレクトリが一覧表示されます。

  • リクエストでプレフィックスを指定し、区切り文字をスラッシュ (/) に設定すると、ディレクトリ内で指定されたプレフィックスで始まる名前のオブジェクトとサブディレクトリが一覧表示されます。 各サブディレクトリは、CommonPrefixesで単一の結果要素としてリストされます。 これらのサブディレクトリ内のオブジェクトおよびディレクトリはリストされません。

たとえば、バケットにはoss.jpgfun/test.jpgfun/movie/001.avifun/movie/007.aviのオブジェクトが含まれています。 ディレクトリ区切り文字としてスラッシュ (/) を指定します。 次の例では、シミュレートされたディレクトリにオブジェクトを一覧表示します。

バケット内のすべてのオブジェクトを一覧表示する

  • 次のサンプルコードは、GetBucket (ListObjects) 操作を呼び出してバケット内のすべてのオブジェクトを一覧表示する方法の例を示しています。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a request to list objects. 
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
    
                // List objects. 
                ObjectListing listing = ossClient.listObjects(listObjectsRequest);
    
                // Traverse all objects. 
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all CommonPrefix elements. 
                System.out.println("CommonPrefixes:");
                for (String commonPrefix : listing.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } 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();
                }
            }
        }
    }
  • 次のサンプルコードでは、GetBucketV2 (ListObjectsV2) 操作を呼び出してバケット内のすべてのオブジェクトを一覧表示する方法の例を示します。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // List objects. 
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // Traverse all objects. 
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all CommonPrefix elements. 
                System.out.println("CommonPrefixes:");
                for (String commonPrefix : result.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } 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();
                }
            }
        }
    }
  • レスポンスパラメーター

    バケット内のすべてのオブジェクトを一覧表示する前述の2つのメソッドに対して、次のレスポンスが返されます。

    Objects:
    fun/movie/001.avi
    fun/movie/007.avi
    fun/test.jpg
    oss.jpg
    CommonPrefixes:                    

ディレクトリ内のすべてのオブジェクトを一覧表示する

  • 次のサンプルコードは、GetBucket (ListObjects) 操作を呼び出してディレクトリ内のすべてのオブジェクトを一覧表示する方法の例を示しています。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a request to list objects. 
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
                // Set prefix to fun/ to list all objects in the fun/ directory. 
                listObjectsRequest.setPrefix("fun/");
    
                // Lists all objects in the fun/ directory. 
                ObjectListing listing = ossClient.listObjects(listObjectsRequest);
    
                // Traverse all objects. 
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all CommonPrefix elements. 
                System.out.println("\nCommonPrefixes:");
                for (String commonPrefix : listing.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } 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();
                }
            }
        }
    }
  • 次のサンプルコードでは、GetBucketV2 (ListObjectsV2) 操作を呼び出して、特定のディレクトリ内のすべてのオブジェクトを一覧表示する方法の例を示します。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a ListObjectsV2Request request to list objects. 
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // Set prefix to fun/ to list all objects in the fun/ directory. 
                listObjectsV2Request.setPrefix("fun/");
    
                // Initiate the request. 
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // Traverse all objects. 
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all CommonPrefix elements. 
                System.out.println("\nCommonPrefixes:");
                for (String commonPrefix : result.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } 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();
                }
            }
        }
    }
  • 指定したディレクトリ内のすべてのオブジェクトを一覧表示する上記の2つの操作に対して、次の応答が返されます。

    Objects:
    fun/movie/001.avi
    fun/movie/007.avi
    fun/test.jpg
    CommonPrefixes:                    

特定のディレクトリ内のオブジェクトとサブディレクトリの一覧表示

  • 次のサンプルコードでは、GetBucket (ListObjects) 操作を呼び出して、特定のディレクトリ内のオブジェクトとサブディレクトリを一覧表示する方法の例を示します。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a request to list objects. 
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
    
                // Set the delimiter to a forward slash (/). 
                listObjectsRequest.setDelimiter("/");
    
                // List all objects and subdirectories in the fun/ directory. 
                listObjectsRequest.setPrefix("fun/");
    
                ObjectListing listing = ossClient.listObjects(listObjectsRequest);
    
                // Traverse all objects. 
                System.out.println("Objects:");
                // In the response, objectSummaries lists the objects in the fun/ directory. 
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all CommonPrefix elements. 
                System.out.println("\nCommonPrefixes:");
                // CommonPrefixs lists all subdirectories in the fun/ directory. The fun/movie/001.avi and fun/movie/007.avi objects are not listed because they are in the movie/ subdirectory of the fun/ directory. 
                for (String commonPrefix : listing.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } 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();
                }
            }
        }
    }
  • 次のサンプルコードでは、GetBucketV2 (ListObjectsV2) 操作を呼び出して、ディレクトリ内のオブジェクトとサブディレクトリを一覧表示する方法の例を示します。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a ListObjectsV2Request request to list objects. 
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // Set Prefix to fun/ to list all objects and subdirectories in the fun/ directory. 
                listObjectsV2Request.setPrefix("fun/");
    
                // Set the delimiter to a forward slash (/). 
                listObjectsV2Request.setDelimiter("/");
    
                // Initiate the request. 
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // Traverse all objects. 
                System.out.println("Objects:");
                // In the response, objectSummaries lists the objects in the fun/ directory. 
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all CommonPrefix elements. 
                System.out.println("\nCommonPrefixes:");
                // CommonPrefixs lists all subdirectories in the fun/ directory. The fun/movie/001.avi and fun/movie/007.avi objects are not listed because they are in the movie/ subdirectory of the fun/ directory. 
                for (String commonPrefix : result.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } 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();
                }
            }
        }
    }
  • 上記の2つの操作を呼び出して、指定したディレクトリ内のオブジェクトとサブディレクトリを一覧表示すると、次の応答が返されます。

    Objects:
    fun/test.jpg
    
    CommonPrefixes:
    fun/movie/                    

特定のディレクトリ内のオブジェクトのサイズを一覧表示する

  • 次のサンプルコードでは、GetBucket (ListObjects) 操作を呼び出して、特定のディレクトリ内のオブジェクトのサイズを一覧表示する方法の例を示します。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. If you want to traverse the sizes of objects and directories in the root directory, leave this parameter empty. 
            String keyPrefix = "exampledir/object";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build(););
    
            try {
                ObjectListing objectListing = null;
                do {
                    // By default, 100 objects or directories are listed at a time. 
                    ListObjectsRequest request = new ListObjectsRequest(bucketName).withDelimiter("/").withPrefix(keyPrefix);
                    if (objectListing != null) {
                        request.setMarker(objectListing.getNextMarker());
                    }
                    objectListing = ossClient.listObjects(request);
                    List<String> folders = objectListing.getCommonPrefixes();
                    for (String folder : folders) {
                        System.out.println(folder + " : " + (calculateFolderLength(ossClient, bucketName, folder) / 1024) + "KB");
                    }
                    List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                    for (OSSObjectSummary s : sums) {
                        System.out.println(s.getKey() + " : " + (s.getSize() / 1024) + "KB");
                    }
                } while (objectListing.isTruncated());
            } 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();
                }
            }
        }
    
        // List the sizes of objects in a specific directory in a bucket. 
        private static long calculateFolderLength(OSS ossClient, String bucketName, String folder) {
            long size = 0L;
            ObjectListing objectListing = null;
            do {
                // The default value of MaxKeys is 100. The maximum value of MaxKeys is 1000. 
                ListObjectsRequest request = new ListObjectsRequest(bucketName).withPrefix(folder).withMaxKeys(1000);
                if (objectListing != null) {
                    request.setMarker(objectListing.getNextMarker());
                }
                objectListing = ossClient.listObjects(request);
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    size += s.getSize();
                }
            } while (objectListing.isTruncated());
            return size;
        }
    }
  • 次のサンプルコードでは、GetBucketV2 (ListObjectsV2) 操作を呼び出して、ディレクトリ内のオブジェクトのサイズを一覧表示する方法の例を示します。

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the prefix in the names of the objects that you want to list. Example: exampledir/object. If you want to traverse the sizes of objects and directories in the root directory, leave this parameter empty. 
            String keyPrefix = "exampledir/object";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                ListObjectsV2Result result = null;
                do {
                    // By default, 100 objects or directories are listed at a time. 
                    ListObjectsV2Request request = new ListObjectsV2Request(bucketName).withDelimiter("/").withPrefix(keyPrefix);
                    if (result != null) {
                        request.setContinuationToken(result.getNextContinuationToken());
                    }
                    result = ossClient.listObjectsV2(request);
                    List<String> folders = result.getCommonPrefixes();
                    for (String folder : folders) {
                        System.out.println(folder + " : " + (calculateFolderLength(ossClient, bucketName, folder) / 1024) + "KB");
                    }
                    List<OSSObjectSummary> sums = result.getObjectSummaries();
                    for (OSSObjectSummary s : sums) {
                        System.out.println(s.getKey() + " : " + (s.getSize() / 1024) + "KB");
                    }
                } while (result.isTruncated());
            } 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();
                }
            }
        }
    
        // List the sizes of objects in a specific directory in a bucket. 
        private static long calculateFolderLength(OSS ossClient, String bucketName, String folder) {
            long size = 0L;
            ListObjectsV2Result result = null;
            do {
                // The default value of MaxKeys is 100. The maximum value of MaxKeys is 1000. 
                ListObjectsV2Request request = new ListObjectsV2Request(bucketName).withPrefix(folder).withMaxKeys(1000);
                if (result != null) {
                    request.setContinuationToken(result.getNextContinuationToken());
                }
                result = ossClient.listObjectsV2(request);
                List<OSSObjectSummary> sums = result.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    size += s.getSize();
                }
            } while (result.isTruncated());
            return size;
        }
    }

関連ドキュメント

  • オブジェクトの一覧表示に使用する完全なサンプルコードについては、『GitHub』をご参照ください。

  • オブジェクトを一覧表示するために呼び出すAPI操作の詳細については、「GetBucket (ListObjects) 」および「ListObjectsV2 (GetBucketV2) 」をご参照ください。

  • LiveChannelsを一覧表示および管理する方法の詳細については、「LiveChannelsの管理」をご参照ください。