Tous les produits
Search
Centre de documentation

Object Storage Service:Répertorier les objets (OSS SDK for Java 1.0)

Dernière mise à jour :Aug 08, 2026

Cette rubrique explique comment répertorier tous les objets, un nombre spécifique d'objets et les objets dont les noms contiennent un préfixe spécifique dans un bucket Object Storage Service (OSS).

Notes d'utilisation

  • Dans cette rubrique, l'endpoint public de la région Chine (Hangzhou) est utilisé. Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et endpoints pris en charge, consultez Régions et endpoints.

  • Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour plus d'informations, consultez Configuration des identifiants d'accès.

  • Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification avec des identifiants du Security Token Service (STS), consultez Configuration du client.

  • Pour répertorier les objets, vous devez disposer de l'autorisation oss:ListObjects. Pour plus d'informations, consultez Accorder une politique personnalisée.

Informations contextuelles

    • GetBucket (ListObjects)

      Vous pouvez appeler l'opération GetBucket (ListObjects) dans l'un des formats suivants :

      • ObjectListing listObjects(String bucketName) : répertorie tous les objets d'un bucket. Par défaut, jusqu'à 100 objets peuvent être répertoriés dans une seule requête.

      • ObjectListing listObjects(String bucketName, String prefix) : répertorie les objets dont les noms contiennent un préfixe spécifique dans un bucket. Par défaut, jusqu'à 100 objets peuvent être répertoriés par une seule requête.

      • ObjectListing listObjects(ListObjectsRequest listObjectsRequest) : répertorie les objets qui répondent aux conditions spécifiées. Utilisez ce format pour répertorier les objets de manière flexible.

      Le tableau suivant décrit les paramètres que vous pouvez spécifier lors de l'appel de l'opération GetBucket (ListObjects).

      Paramètre

      Description

      Méthode

      objectSummaries

      Les métadonnées des objets que vous souhaitez répertorier.

      List<OSSObjectSummary> getObjectSummaries()

      prefix

      Le préfixe dans les noms des objets que vous souhaitez répertorier.

      String getPrefix()

      delimiter

      Le caractère utilisé pour regrouper les objets que vous souhaitez répertorier par nom.

      String getDelimiter()

      marker

      La position à partir de laquelle l'opération de liste commence.

      String getMarker()

      maxKeys

      Le nombre maximal d'objets pouvant être répertoriés à la fois.

      int getMaxKeys()

      nextMarker

      La position à partir de laquelle la prochaine opération de liste commence.

      String getNextMarker()

      isTruncated

      Indique si la liste des objets est tronquée. Valeurs valides :

      • false : Tous les objets sont répertoriés sans troncature.

      • true : Seule une partie des objets est répertoriée.

      boolean isTruncated()

      commonPrefixes

      Un ensemble de sous-chaînes de noms d'objets. Les objets dont les noms se terminent par le délimiteur et contiennent le même préfixe sont regroupés en un seul élément de résultat dans CommonPrefixes.

      List<String> getCommonPrefixes()

      encodingType

      Le type d'encodage des noms d'objets dans la réponse.

      String getEncodingType()

    • GetBucketV2 (ListObjectsV2)

      Vous pouvez appeler l'opération GetBucketV2 (ListObjectsV2) dans l'un des formats suivants :

      • ListObjectsV2Result listObjectsV2(String bucketName) : répertorie tous les objets d'un bucket. Par défaut, jusqu'à 100 objets peuvent être répertoriés par une seule requête.

      • ListObjectsV2Result listObjectsV2(String bucketName, String prefix) : répertorie les objets dont les noms contiennent un préfixe spécifique dans un bucket. Par défaut, jusqu'à 100 objets peuvent être répertoriés par une seule requête.

      • ListObjectsV2Result listObjectsV2(ListObjectsRequest listObjectsRequest) : répertorie les objets qui répondent aux conditions spécifiées. Utilisez ce format pour répertorier les objets de manière flexible.

      Le tableau suivant décrit les paramètres que vous pouvez spécifier lors de l'appel de l'opération GetBucketV2 (ListObjectsV2).

      Paramètre

      Description

      Méthode

      objectSummaries

      Les métadonnées des objets que vous souhaitez répertorier.

      List<OSSObjectSummary> getObjectSummaries()

      prefix

      Le préfixe dans les noms des objets que vous souhaitez répertorier.

      String getPrefix()

      delimiter

      Le caractère utilisé pour regrouper les objets que vous souhaitez répertorier par nom.

      String getDelimiter()

      startAfter

      La position à partir de laquelle l'opération de liste commence.

      String getStartAfter()

      maxKeys

      Le nombre maximal d'objets pouvant être répertoriés à la fois.

      int getMaxKeys()

      continuationToken

      La position à partir de laquelle l'opération de liste commence.

      String getContinuationToken()

      nextContinuationToken

      La position à partir de laquelle la prochaine opération de liste commence.

      String getNextContinuationToken()

      isTruncated

      Indique si la liste des objets est tronquée. Valeurs valides :

      • false : Tous les objets sont répertoriés sans troncature.

      • true : Seule une partie des objets est répertoriée.

      boolean isTruncated()

      commonPrefixes

      Un ensemble de sous-chaînes de noms d'objets. Les objets dont les noms se terminent par le délimiteur et contiennent le même préfixe sont regroupés en un seul élément de résultat dans CommonPrefixes.

      List<String> getCommonPrefixes()

      encodingType

      Le type d'encodage des noms d'objets dans la réponse.

      String getEncodingType()

      fetchOwner

      Indique s'il faut inclure les informations sur le propriétaire de l'objet dans la réponse. Valeurs valides :

      • true : La réponse inclut les informations sur le propriétaire de l'objet.

      • false : La réponse n'inclut pas les informations sur le propriétaire de l'objet.

      String getFetchOwner()

    Répertorier les objets à l'aide d'une liste simple

    Vous pouvez appeler l'opération GetBucket (ListObjects) ou l'opération GetBucketV2 (ListObjectsV2) pour répertorier les objets dans un bucket spécifique.

    Appeler l'opération GetBucket (ListObjects) pour répertorier les objets

    L'exemple de code suivant montre comment appeler l'opération GetBucket (ListObjects) pour répertorier les objets dans un bucket spécifique. Par défaut, 100 objets sont répertoriés dans une requête.

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use. 
            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();
                }
            }
        }
    }                  

    Appeler l'opération GetBucketV2 (ListObjectsV2) pour répertorier les objets

    L'exemple de code suivant montre comment appeler l'opération GetBucketV2 (ListObjectsV2) pour répertorier les objets dans un bucket spécifique. Par défaut, 100 objets sont répertoriés par une requête.

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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. 
            // Call the shutdown method to release resources when the OSSClient is no longer in use.
            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();
                }
            }
        }
    }

    Appeler l'opération ListObjectsRequest pour répertorier les objets

    Vous pouvez spécifier des paramètres lors de l'appel de l'opération ListObjectsRequest afin de répertorier les objets avec flexibilité. Le tableau suivant présente les paramètres que vous pouvez spécifier lorsque vous appelez l'opération ListObjectsRequest.

    Paramètre

    Description

    Méthode

    prefix

    Le préfixe que les noms des objets à lister doivent inclure.

    setPrefix(String prefix)

    delimiter

    Caractère utilisé pour regrouper les objets par nom. Par exemple, vous pouvez définir le délimiteur sur une barre oblique (/). Les objets dont les noms contiennent la même chaîne s'étendant du préfixe spécifié jusqu'à la première occurrence de la barre oblique (/) sont regroupés en tant qu'élément CommonPrefixes. Tous les objets dont les noms contiennent ces éléments CommonPrefixes sont répertoriés. Utilisez le paramètre delimiter pour gérer et interroger les objets de manière hiérarchique, ce qui garantit des résultats de requête plus organisés et intuitifs.

    setDelimiter(String delimiter)

    marker

    Position à partir de laquelle l'opération de liste commence. Seuls les objets dont les noms viennent après la valeur de marker dans l'ordre alphabétique sont listés.

    setMarker(String marker)

    maxKeys

    Nombre maximal d'objets pouvant être listés en une seule fois. Une fois ce paramètre spécifié, les objets sont listés par ordre alphabétique. Valeur maximale : 1000. Valeur par défaut : 100.

    setMaxKeys(Integer maxKeys)

    encodingType

    Type d'encodage des noms d'objets dans la réponse. Valeur valide : URL.

    setEncodingType(String encodingType)

    Lister un nombre spécifique d'objets

    L'exemple de code suivant montre comment lister un nombre spécifique d'objets dans un bucket :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.
            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();
                }
            }
        }
    }                    

    Lister les objets dont les noms contiennent un préfixe spécifique

    L'exemple de code suivant montre comment lister les objets dont les noms contiennent un préfixe spécifique dans un bucket :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use. 
            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();
                }
            }
        }
    }                    

    Lister les objets dont les noms viennent après la valeur de marker dans l'ordre alphabétique

    L'exemple de code suivant montre comment lister les objets dont les noms viennent après la valeur de marker dans l'ordre alphabétique :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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 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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use. 
            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();
                }
            }
        }
    }

    Lister tous les objets d'un bucket par page

    L'exemple de code suivant montre comment lister tous les objets d'un bucket par page. Vous pouvez utiliser maxKeys pour spécifier le nombre maximal d'objets pouvant être listés sur chaque page.

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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";
            // 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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use. 
            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();
                }
            }
        }
    }

    Lister par page les objets dont les noms contiennent un préfixe spécifique

    L'exemple de code suivant montre comment lister par page les objets dont les noms contiennent un préfixe spécifique :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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";
            // 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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use. 
            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();
                }
            }
        }
    }

    Lister les objets dont les noms sont encodés avec un type d'encodage spécifique

    Si le nom d'un objet contient l'un des caractères suivants, il doit être encodé en URL avant sa transmission. OSS prend uniquement en charge l'encodage URL.

    • Guillemets simples (')

    • Guillemets doubles (")

    • Esperluettes (&)

    • Chevrons (<>)

    • Virgules chinoises (、)

    • Caractères chinois

    L'exemple de code suivant montre comment lister les objets dont les noms sont encodés avec un type d'encodage spécifique :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Appeler l'opération ListObjectsV2Request pour répertorier les objets

    Lorsque vous appelez l'opération ListObjectsV2Request, vous pouvez spécifier des paramètres afin de répertorier les objets avec flexibilité. Par exemple, il est possible de lister un nombre défini d'objets, ceux dont le nom contient un préfixe spécifique ou tous les objets d'un compartiment (bucket) par page.

    Le tableau suivant présente les paramètres que vous pouvez spécifier lors de l'appel de l'opération ListObjectsV2Request.

    Parameter

    Description

    Method

    prefix

    Préfixe que doivent contenir les noms des objets à lister.

    setPrefix(String prefix)

    delimiter

    Caractère utilisé pour regrouper les objets par nom. Par exemple, vous pouvez définir le délimiteur sur une barre oblique (/). Les objets dont les noms contiennent la même chaîne s'étendant du préfixe spécifié jusqu'à la première occurrence de la barre oblique (/) sont regroupés en tant qu'élément CommonPrefixes. Tous les objets dont les noms contiennent les éléments CommonPrefixes sont répertoriés. Utilisez le paramètre delimiter pour gérer et interroger les objets de manière hiérarchique, ce qui garantit des résultats de requête plus organisés et intuitifs.

    setDelimiter(String delimiter)

    maxKeys

    Nombre maximal d'objets pouvant être listés en une seule fois. Après avoir spécifié ce paramètre, les objets sont listés par ordre alphabétique. Valeur maximale : 1000. Valeur par défaut : 100.

    setMaxKeys(Integer maxKeys)

    startAfter

    Position à partir de laquelle l'opération de liste commence. Les objets dont les noms viennent après la valeur de startAfter dans l'ordre alphabétique sont listés.

    setStartAfter(String startAfter)

    continuationToken

    Jeton continuationToken utilisé dans cette opération de liste.

    setContinuationToken(String continuationToken)

    encodingType

    Type d'encodage des noms d'objets dans la réponse. Valeur valide : URL.

    setEncodingType(String encodingType)

    fetchOwner

    Indique si les informations relatives au propriétaire doivent être incluses dans la réponse.

    setFetchOwner(boolean fetchOwner )

    Lister un nombre spécifique d'objets

    L'exemple de code suivant montre comment lister un nombre spécifique d'objets dans un bucket :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Lister les objets dont les noms contiennent un préfixe spécifique

    L'exemple de code suivant montre comment lister les objets dont les noms contiennent un préfixe spécifique dans un bucket :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Lister les objets dont les noms viennent après la valeur de startAfter dans l'ordre alphabétique

    L'exemple de code suivant montre comment lister les objets dont les noms viennent après la valeur de startAfter dans l'ordre alphabétique :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Lister les objets et leurs informations de propriétaire

    L'exemple de code suivant montre comment lister les objets et leurs informations de propriétaire :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Lister tous les objets d'un bucket par page

    L'exemple de code suivant montre comment lister tous les objets d'un bucket par page. Vous pouvez utiliser maxKeys pour spécifier le nombre maximal d'objets pouvant être listés sur chaque page.

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Lister par page les objets dont les noms contiennent un préfixe spécifique

    L'exemple de code suivant montre comment lister par page les objets dont les noms contiennent un préfixe spécifique :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Lister les objets dont les noms sont encodés avec un type d'encodage spécifique

    L'exemple de code suivant montre comment lister les objets dont les noms sont encodés avec un type d'encodage spécifique :

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    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.
            // Call the shutdown method to release resources when the OSSClient is no longer in use.  
            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();
                }
            }
        }
    }

    Répertorier les objets par répertoire

    OSS utilise une structure à plat pour stocker les objets. Un répertoire est un objet de zéro octet dont le nom se termine par une barre oblique (/). Vous pouvez télécharger et envoyer cet objet. Par défaut, un objet dont le nom se termine par une barre oblique (/) s'affiche sous la forme d'un répertoire dans la console OSS. Pour obtenir l'exemple de code complet utilisé pour créer des répertoires, consultez GitHub.

    Vous pouvez spécifier les paramètres delimiter et prefix pour répertorier les objets par répertoire.

    • Si vous définissez le paramètre prefix sur un nom de répertoire dans la requête, les objets et sous-répertoires dont les noms contiennent ce préfixe sont répertoriés.

    • Si vous spécifiez un préfixe et définissez le paramètre delimiter sur une barre oblique (/) dans la requête, seuls les objets et sous-répertoires dont les noms commencent par le préfixe spécifié dans le répertoire sont répertoriés. Chaque sous-répertoire apparaît comme un seul élément de résultat dans CommonPrefixes. Les objets et répertoires contenus dans ces sous-répertoires ne sont pas listés.

    Par exemple, un bucket contient les objets suivants : oss.jpg, fun/test.jpg, fun/movie/001.avi, et fun/movie/007.avi. La barre oblique (/) est spécifiée comme délimiteur de répertoire. Les exemples suivants décrivent comment répertorier les objets dans des répertoires simulés.

    Répertorier tous les objets du bucket

    • L'exemple de code suivant montre comment appeler l'opération GetBucket (ListObjects) pour répertorier tous les objets du bucket :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.*;
      import com.aliyun.oss.common.comm.SignVersion;
      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.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              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();
                  }
              }
          }
      }
    • L'exemple de code suivant montre comment appeler l'opération GetBucketV2 (ListObjectsV2) pour répertorier tous les objets d'un bucket :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.*;
      import com.aliyun.oss.common.comm.SignVersion;
      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.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              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();
                  }
              }
          }
      }
    • Paramètres de réponse

      La réponse suivante est renvoyée pour les deux méthodes précédentes qui répertorient tous les objets d'un bucket :

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

    Répertorier tous les objets d'un répertoire

    • L'exemple de code suivant montre comment appeler l'opération GetBucket (ListObjects) pour répertorier tous les objets d'un répertoire :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.*;
      import com.aliyun.oss.common.comm.SignVersion;
      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.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              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();
                  }
              }
          }
      }
    • L'exemple de code suivant montre comment appeler l'opération GetBucketV2 (ListObjectsV2) pour répertorier tous les objets d'un répertoire spécifique :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.*;
      import com.aliyun.oss.common.comm.SignVersion;
      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.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              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();
                  }
              }
          }
      }
    • La réponse suivante est renvoyée pour les deux opérations précédentes qui répertorient tous les objets du répertoire spécifié :

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

    Répertorier les objets et sous-répertoires d'un répertoire spécifique

    • L'exemple de code suivant montre comment appeler l'opération GetBucket (ListObjects) pour répertorier les objets et sous-répertoires d'un répertoire spécifique :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.*;
      import com.aliyun.oss.common.comm.SignVersion;
      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.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              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();
                  }
              }
          }
      }
    • L'exemple de code suivant montre comment appeler l'opération GetBucketV2 (ListObjectsV2) pour répertorier les objets et sous-répertoires d'un répertoire :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.*;
      import com.aliyun.oss.common.comm.SignVersion;
      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.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              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();
                  }
              }
          }
      }
    • La réponse suivante est renvoyée lorsque vous appelez les deux opérations précédentes pour répertorier les objets et sous-répertoires du répertoire spécifié :

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

    Répertorier la taille des objets d'un répertoire spécifique

    • L'exemple de code suivant montre comment appeler l'opération GetBucket (ListObjects) pour répertorier la taille des objets d'un répertoire spécifique :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.CredentialsProviderFactory;
      import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
      import com.aliyun.oss.common.comm.SignVersion;
      import com.aliyun.oss.model.OSSObjectSummary;
      import com.aliyun.oss.model.ObjectListing;
      
      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";
              // Specify the prefix in the names of the objects that you want to list. Example: exampledir/. If you want to traverse the sizes of objects and directories in the root directory, leave this parameter empty. 
              String prefix = "exampledir/";
      
              // Create an OSSClient instance.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
              clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
              OSS ossClient = OSSClientBuilder.create()
                      .endpoint(endpoint)
                      .credentialsProvider(credentialsProvider)
                      .clientConfiguration(clientBuilderConfiguration)
                      .region(region)
                      .build();
      
              try {
                  long totalSize = 0;
                  int totalCount = 0;
                  String nextMarker = null;
                  final int maxKeys = 1000;
      
                  do {
                      ObjectListing objectListing = ossClient.listObjects(bucketName, prefix);
                      for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                          totalSize += objectSummary.getSize();
                          totalCount++;
                          // Output the name and size of each object.
                          System.out.println("File: " + objectSummary.getKey() + " | Size: " + objectSummary.getSize() + " bytes (" + formatSize(objectSummary.getSize()) + ")");
                      }
                      nextMarker = objectListing.getNextMarker();
                  } while (nextMarker != null && !nextMarker.isEmpty());
      
                  System.out.println("Folder: " + prefix);
                  System.out.println("Total objects: " + totalCount);
                  System.out.println("Total size (bytes): " + totalSize);
                  System.out.println("Total size (human readable): " + formatSize(totalSize));
              } 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();
                  }
              }
          }
      
          // Convert bytes into a readable format.
          public static String formatSize(long size) {
              String[] units = {"B", "KB", "MB", "GB", "TB", "PB"};
              int unitIndex = 0;
              double sizeD = size;
              while (sizeD >= 1024 && unitIndex < units.length - 1) {
                  sizeD /= 1024;
                  unitIndex++;
              }
              return String.format("%.2f %s", sizeD, units[unitIndex]);
          }
      }
      
    • L'exemple de code suivant montre comment appeler l'opération GetBucketV2 (ListObjectsV2) pour répertorier la taille des objets d'un répertoire :

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.auth.CredentialsProviderFactory;
      import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
      import com.aliyun.oss.common.comm.SignVersion;
      import com.aliyun.oss.model.ListObjectsV2Request;
      import com.aliyun.oss.model.ListObjectsV2Result;
      import com.aliyun.oss.model.OSSObjectSummary;
      
      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";
              // Specify the prefix in the names of the objects that you want to list. Example: exampledir/. If you want to traverse the sizes of objects and directories in the root directory, leave this parameter empty. 
              String prefix = "exampledir/";
      
              // Create an OSSClient instance.
              // Call the shutdown method to release resources when the OSSClient is no longer in use.  
              ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
              clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
              OSS ossClient = OSSClientBuilder.create()
                      .endpoint(endpoint)
                      .credentialsProvider(credentialsProvider)
                      .clientConfiguration(clientBuilderConfiguration)
                      .region(region)
                      .build();
      
              try {
                  long totalSize = 0;
                  int totalCount = 0;
                  String continuationToken = null;
                  final int maxKeys = 1000;
      
                  do {
                      ListObjectsV2Request request = new ListObjectsV2Request(bucketName)
                              .withPrefix(prefix)
                              .withMaxKeys(maxKeys)
                              .withContinuationToken(continuationToken);
      
                      ListObjectsV2Result result = ossClient.listObjectsV2(request);
      
                      for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                          totalSize += objectSummary.getSize();
                          totalCount++;
                          System.out.println("File: " + objectSummary.getKey() + " | Size: " + objectSummary.getSize() + " bytes (" + formatSize(objectSummary.getSize()) + ")");
                      }
      
                      continuationToken = result.getNextContinuationToken();
                  } while (continuationToken != null);
      
                  System.out.println("\nFolder: " + prefix);
                  System.out.println("Total objects: " + totalCount);
                  System.out.println("Total size (bytes): " + totalSize);
                  System.out.println("Total size (human readable): " + formatSize(totalSize));
              }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();
                  }
              }
          }
      
          // Convert bytes into a readable format.
          public static String formatSize(long size) {
              String[] units = {"B", "KB", "MB", "GB", "TB", "PB"};
              int unitIndex = 0;
              double sizeD = size;
              while (sizeD >= 1024 && unitIndex < units.length - 1) {
                  sizeD /= 1024;
                  unitIndex++;
              }
              return String.format("%.2f %s", sizeD, units[unitIndex]);
          }
      }
      

    Références