All Products
Search
Document Center

Object Storage Service:List objects (Java SDK V1)

Last Updated:Mar 28, 2026

Learn how to list all objects, a specified number of objects, and objects with a specific prefix in an OSS bucket.

Notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information, see Configure access credentials.

  • This topic demonstrates creating an OSSClient instance with an OSS endpoint. For alternative configurations, such as using a custom domain or authenticating with credentials from Security Token Service (STS), see Client configuration.

  • To list objects, you must have the oss:ListObjects permission. For details, see Attach a custom policy to a RAM user.

Background

You can call the GetBucket (ListObjects) or GetBucketV2 (ListObjectsV2) operation to list up to 1,000 objects in a bucket in a single call. You can specify parameters to filter the results. For example, you can list objects from a specific starting point, list objects and subdirectories within a specified directory, or use pagination to list more than 1,000 objects. The main differences between these two operations are as follows:

  • The GetBucket (ListObjects) operation returns owner information by default.

  • To include owner information in the response from the GetBucketV2 (ListObjectsV2) operation, you must set the fetchOwner parameter.

    Note

    Use the GetBucketV2 (ListObjectsV2) operation to list objects in buckets with versioning enabled.

The following sections describe the parameters for the GetBucket (ListObjects) and GetBucketV2 (ListObjectsV2) operations.

  • List objects using the GetBucket (ListObjects) operation

    You can call the GetBucket (ListObjects) operation in one of the following formats:

    • ObjectListing listObjects(String bucketName): Lists up to 100 objects in a bucket by default.

    • ObjectListing listObjects(String bucketName, String prefix): Lists up to 100 objects in a bucket that have a specific prefix by default.

    • ObjectListing listObjects(ListObjectsRequest listObjectsRequest): Provides multiple filter options for flexible queries.

    The following table describes the parameters for the GetBucket (ListObjects) operation.

    Parameter

    Description

    Method

    objectSummaries

    A list of object metadata.

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    The prefix that the names of returned objects must contain.

    String getPrefix()

    delimiter

    The character used to group object names.

    String getDelimiter()

    marker

    The object key to start the listing from.

    String getMarker()

    maxKeys

    The maximum number of objects to return.

    int getMaxKeys()

    nextMarker

    The object key to use as the marker for the next request. This parameter appears only when the response is truncated.

    String getNextMarker()

    isTruncated

    Indicates whether the returned list of objects is truncated.

    • false: The list of objects is not truncated.

    • true: The list of objects is truncated.

    boolean isTruncated()

    commonPrefixes

    A collection of object name prefixes that are grouped by the specified delimiter.

    List<String> getCommonPrefixes()

    encodingType

    The encoding type of the object names in the response.

    String getEncodingType()

  • List objects using the GetBucketV2 (ListObjectsV2) operation

    You can call the GetBucketV2 (ListObjectsV2) operation in one of the following formats:

    • ListObjectsV2Result listObjectsV2(String bucketName): Lists up to 100 objects in a bucket by default.

    • ListObjectsV2Result listObjectsV2(String bucketName, String prefix): Lists up to 100 objects in a bucket that have a specific prefix by default.

    • ListObjectsV2Result listObjectsV2(ListObjectsRequest listObjectsRequest): Provides multiple filter options for flexible queries.

    The following table describes the parameters for the GetBucketV2 (ListObjectsV2) operation.

    Parameter

    Description

    Method

    objectSummaries

    A list of object metadata.

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    The prefix that the names of returned objects must contain.

    String getPrefix()

    delimiter

    The character used to group object names.

    String getDelimiter()

    startAfter

    The object key to start the listing after.

    String getStartAfter()

    maxKeys

    The maximum number of objects to return.

    int getMaxKeys()

    continuationToken

    A token from a previous truncated response that specifies where to continue the listing.

    String getContinuationToken()

    nextContinuationToken

    A token for retrieving the next page of results. This parameter appears only when the response is truncated.

    String getNextContinuationToken()

    isTruncated

    Indicates whether the returned list of objects is truncated.

    • false: The list of objects is not truncated.

    • true: The list of objects is truncated.

    boolean isTruncated()

    commonPrefixes

    A collection of object name prefixes that are grouped by the specified delimiter.

    List<String> getCommonPrefixes()

    encodingType

    The encoding type of the object names in the response.

    String getEncodingType()

    fetchOwner

    Specifies whether to include the owner information in the response.

    • true: The owner information is included in the response.

    • false: The owner information is not included in the response.

    String getFetchOwner()

List objects

You can call the GetBucket (ListObjects) operation or the GetBucketV2 (ListObjectsV2) operation to list objects in a specific bucket.

GetBucket (ListObjects)

The following sample code shows how to call the GetBucket (ListObjects) operation to list objects in a bucket. By default, each request returns up to 100 objects.

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 {
        // This example uses the endpoint for the China (Hangzhou) region. Use 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 object prefix. 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.
        // When the OSSClient instance is no longer in use, call the shutdown method to release its resources.
        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 keyPrefix is not set, all objects in the bucket are listed. If keyPrefix is set, only objects with 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. This means your request reached OSS but was rejected with an error.");
            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 a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                  

GetBucketV2 (ListObjectsV2)

The following sample code shows how to call the GetBucketV2 (ListObjectsV2) operation to list objects in a bucket. By default, each request returns up to 100 objects.

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 {
        // This example uses the endpoint for the China (Hangzhou) region. Use 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 object prefix. 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.
        // When the OSSClient instance is no longer in use, call the shutdown method to release its resources.
        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 keyPrefix is not set, all objects in the bucket are listed. If keyPrefix is set, only objects with 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. This means your request reached OSS but was rejected with an error.");
            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 a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

List objects by using ListObjectsRequest

Set the parameters of ListObjectsRequest to perform flexible queries. The following table describes each parameter.

Parameter

Description

Method

prefix

Limits the response to objects whose names begin with the specified prefix.

setPrefix(String prefix)

delimiter

A character for grouping object keys. Keys that contain the same string from the prefix to the first delimiter are grouped into a single CommonPrefixes element. Use this to list objects hierarchically, like in a file system.

setDelimiter(String delimiter)

marker

Specifies the key to start listing from. The response includes only objects with keys that appear lexicographically after the specified marker.

setMarker(String marker)

maxKeys

Sets the maximum number of objects to return in the response. The default value is 100. The maximum value is 1000.

setMaxKeys(Integer maxKeys)

encodingType

Specifies the encoding type for object keys in the response. The only valid value is url.

setEncodingType(String encodingType)

List a specific number of objects

The following code example shows how to list a specific number of objects.

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 {
        // This example uses the endpoint for the China (Hangzhou) region. Specify the endpoint for your region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running the code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the bucket's region. For example, if your bucket is in the China (Hangzhou) region, set this parameter to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Set the maximum number of objects to return.
            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 a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                    

List objects with a specified prefix

The following code example shows how to list objects with a specified prefix.

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 {
        // This example uses the endpoint for the China (Hangzhou) region. Specify the endpoint for your region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running the code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the object prefix. For example, exampledir/object.
        String keyPrefix = "exampledir/object";
        // Specify the bucket's region. For example, if your bucket is in the China (Hangzhou) region, set this parameter to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects with the specified prefix. By default, 100 objects are returned.
            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 a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                    

List objects after a specified marker

The following code example shows how to list objects whose keys appear lexicographically after a specified marker.

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 {
        // This example uses the endpoint for the China (Hangzhou) region. Specify the endpoint for your region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running the code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the marker. The response includes only objects with keys that appear lexicographically after the marker.  
        String marker = "ex";
        // Specify the bucket's region. For example, if your bucket is in the China (Hangzhou) region, set this parameter to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects after the specified marker. By default, 100 objects are returned.
            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 a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

List all objects by using pagination

The following code example shows how to list all objects in a bucket by using pagination. The maxKeys parameter specifies the number of objects to return on each 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 {
        // This example uses the endpoint for the China (Hangzhou) region. Specify the endpoint for your region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running the code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Set the number of objects to return per page to 200.
        int maxKeys = 200;
        // Specify the bucket's region. For example, if your bucket is in the China (Hangzhou) region, set this parameter to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        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 a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

List objects with a prefix using pagination

The following code example shows how to use pagination to list objects with a specified prefix.

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 {
        // This example uses the endpoint for the China (Hangzhou) region. Specify the endpoint for your region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running the code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Set the number of objects to return per page to 200.
        int maxKeys = 200;
        // Specify the object prefix. For example, exampledir/object.
        String keyPrefix = "exampledir/object";
        // Specify the object to start listing from. For example, objecttest.txt.
        String nextMarker = "objecttest.txt";
        // Specify the bucket's region. For example, if your bucket is in the China (Hangzhou) region, set this parameter to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        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 a 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();
            }
        }
    }
}

Specify object name encoding

If an object name contains any of the following characters, you must URL-encode the name before transmission. OSS supports only URL encoding.

  • Single quotation mark (')

  • Double quotation mark (")

  • Ampersand (&)

  • Angle brackets (< >)

  • The Chinese enumeration comma ()

  • Chinese characters

The following code shows how to specify the encoding for object names.

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 {
        // This example uses the endpoint for the China (Hangzhou) region. Specify the endpoint for your region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running the code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Set the number of objects to return per page to 200.
        int maxKeys = 200;
        // Specify the object prefix. For example, exampledir/object.
        String keyPrefix = "exampledir/object";
        // Specify the object to start listing from. For example, objecttest.txt.
        String nextMarker = "objecttest.txt";
        // Specify the bucket's region. For example, if your bucket is in the China (Hangzhou) region, set this parameter to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ObjectListing

List objects using ListObjectsV2Request

Set parameters in a ListObjectsV2Request for flexible queries. For example, you can list a specific number of objects, objects with a specified prefix, or all objects in a bucket using pagination.

The following table describes the parameters for ListObjectsV2Request.

Parameter

Description

Method

prefix

Specifies the prefix that the returned object keys must start with.

setPrefix(String prefix)

delimiter

A character, such as a forward slash (/), used to group object keys. Keys that share a common string between the specified prefix and the first occurrence of the delimiter are grouped into a single CommonPrefixes element. This lets you browse objects hierarchically, similar to a file system.

setDelimiter(String delimiter)

maxKeys

The maximum number of objects to return in a single response. The objects are returned in lexicographical order. The default is 100, and the maximum is 1,000.

setMaxKeys(Integer maxKeys)

startAfter

Specifies the key at which to start the listing. The response includes only objects with keys that come lexicographically after this value.

setStartAfter(String startAfter)

continuationToken

A token from a previous, truncated response. Specifying this token retrieves the next page of results.

setContinuationToken(String continuationToken)

encodingType

Specifies the encoding type for object keys in the response. The only valid value is url.

setEncodingType(String encodingType)

fetchOwner

Specifies whether to include object owner information in the response.

setFetchOwner(boolean fetchOwner )

List a specified number of objects

The following code lists a specified number of objects.

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 {
        // The following example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with the name of your bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Set the maximum number of objects to return.
        int maxKeys = 200;
        // Specify the region where the bucket is located. The China (Hangzhou) region is used as an example.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        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, a request returns up to 100 objects. This example sets the maximum number of objects to return to 200.
            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();
            }
        }
    }
}

List objects with a prefix

The following code lists objects with a specified prefix.

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 {
        // The following example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with the name of your bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the object prefix. Example: exampledir/object.
        String prefix = "exampledir/object";
        // Specify the region where the bucket is located. The China (Hangzhou) region is used as an example.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List objects that have 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();
            }
        }
    }
}

List objects starting after a specific key

The following code lists objects starting after a specific key by using the startAfter parameter.

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 {
        // The following example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with the name of your bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the bucket is located. The China (Hangzhou) region is used as an example.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // The response includes only objects with keys that appear lexicographically after the startAfter value.
            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();
            }
        }
    }
}

Include owner information in the results

The following code includes owner information in the list results.

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 {
        // The following example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with the name of your bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the bucket is located. The China (Hangzhou) region is used as an example.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // By default, owner information is not included in the response. To include it, 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();
            }
        }
    }
}

List all objects by page

The following code lists all objects in a bucket by page. The maxKeys parameter determines the number of objects to return per 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 {
        // The following example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with the name of your bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Set the maximum number of objects to return.
        int maxKeys = 200;
        // Specify the region where the bucket is located. The China (Hangzhou) region is used as an example.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        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;

            // To list objects by page, pass the nextContinuationToken from the previous response to the next request.
            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();
            }
        }
    }
}

List objects with a prefix by page

The following code lists objects with a specified prefix by 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 {
        // The following example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with the name of your bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the object prefix. Example: exampledir/object.
        String keyPrefix = "exampledir/object";
        // Set the maximum number of objects to return.
        int maxKeys = 200;
        // Specify the region where the bucket is located. The China (Hangzhou) region is used as an example.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        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 that have 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();
            }
        }
    }
}

Specify object key encoding

The following code shows how to specify the encoding for object keys.

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 {
        // The following example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Replace with the name of your bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the object prefix. Example: exampledir/object.
        String keyPrefix = "exampledir/object";
        // Set the maximum number of objects to return.
        int maxKeys = 200;
        // Specify the region where the bucket is located. The China (Hangzhou) region is used as an example.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        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;

            // If you specify that the response should be URL-encoded, you must decode the prefix, delimiter, startAfter, key, and commonPrefixes values 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 prefix.
                if (result.getPrefix() != null) {
                    String prefix = URLDecoder.decode(result.getPrefix(), "UTF-8");
                    System.out.println("prefix: " + prefix);
                }

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

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

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

                // Decode the common prefixes.
                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();
            }
        }
    }
}

Simulate directories

OSS does not natively support directories; it uses a flat structure that organizes all data as objects. To simulate a directory, create a zero-byte object with a key ending in a forward slash (/). The OSS console displays this as a directory, and you can upload and download it like any other object. For a complete code example of how to create a directory, see the GitHub sample.

You can use the delimiter and prefix parameters to list objects hierarchically, as if in a directory structure:

  • If you set the prefix parameter to a directory name, the operation recursively lists all objects and subdirectories under that path. All results are returned in the Objects list.

  • If you set a prefix and also set the delimiter to a forward slash (/), the operation lists only the objects and immediate subdirectories at the specified path. Objects are returned in the Objects list, and subdirectories are grouped in the CommonPrefixes list. Objects within the subdirectories are not listed.

For example, assume a bucket contains the following objects: oss.jpg, fun/test.jpg, fun/movie/001.avi, and fun/movie/007.avi. The forward slash (/) is the delimiter. The following examples demonstrate how to list these objects as if they are in directories.

List all objects in a bucket

  • List all objects in a bucket by using GetBucket (ListObjects)

    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 {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a ListObjectsRequest.
                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 common prefixes.
                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 a ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • List all objects in a bucket by using GetBucketV2 (ListObjectsV2)

    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 {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            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 objects.
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse common prefixes.
                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 a 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();
                }
            }
        }
    }
  • Result

    Both methods return the following result for listing all objects in the bucket.

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

Recursively list all objects in a directory

  • Recursively list all objects in a directory by using GetBucket (ListObjects)

    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 {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a ListObjectsRequest.
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
                // Set the prefix to list all objects in the 'fun' directory.
                listObjectsRequest.setPrefix("fun/");
    
                // Recursively list 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 common prefixes.
                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 a 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();
                }
            }
        }
    }
  • Recursively list all objects in a directory by using GetBucketV2 (ListObjectsV2)

    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 {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            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.
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // Set the prefix to list all objects in the 'fun' directory.
                listObjectsV2Request.setPrefix("fun/");
    
                // Send the list request.
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // Traverse objects.
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse common prefixes.
                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 a 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();
                }
            }
        }
    }
  • Both methods return the following result for recursively listing all objects in the specified directory.

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

List objects and subdirectories

  • List objects and subdirectories by using GetBucket (ListObjects)

    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 {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a ListObjectsRequest.
                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:");
                // The objectSummaries list contains objects directly within the 'fun/' directory.
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all common prefixes.
                System.out.println("\nCommonPrefixes:");
                // The commonPrefixes list contains all subdirectories within the 'fun/' directory. The objects fun/movie/001.avi and fun/movie/007.avi are not listed here because they are inside the 'movie/' subdirectory.
                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 a ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • List objects and subdirectories by using GetBucketV2 (ListObjectsV2)

    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 {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            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.
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // Set the prefix to list all objects and subdirectories in the 'fun/' directory.
                listObjectsV2Request.setPrefix("fun/");
    
                // Set the delimiter to a forward slash (/).
                listObjectsV2Request.setDelimiter("/");
    
                // Send the list request.
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // Traverse objects.
                System.out.println("Objects:");
                // The objectSummaries list contains objects directly within the 'fun/' directory.
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse common prefixes.
                System.out.println("\nCommonPrefixes:");
                // The commonPrefixes list contains all subdirectories within the 'fun/' directory. The objects fun/movie/001.avi and fun/movie/007.avi are not listed here because they are inside the 'movie/' subdirectory.
                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 a 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();
                }
            }
        }
    }
  • Both methods return the following result for listing objects and subdirectories at the specified path:

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

Calculate directory size

  • Calculate the total size of objects in a directory by using GetBucket (ListObjects)

    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;
    import com.aliyun.oss.model.ListObjectsRequest; 
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";      
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
            // Specify a prefix, such as 'exampledir/'. To traverse the root directory, leave this empty.
            String prefix = "exampledir/";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            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 {
                    ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
                    listObjectsRequest.setPrefix(prefix);
                    listObjectsRequest.setMaxKeys(maxKeys);
                    // Use the marker from the previous response for pagination.
                    listObjectsRequest.setMarker(nextMarker); 
    
                    ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
    
                    if (objectListing.getObjectSummaries().isEmpty()) {
                        break; 
                    }
    
                    for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                        totalSize += objectSummary.getSize();
                        totalCount++;
                        // Print the key 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("\nFolder Prefix: " + (prefix.isEmpty() ? "/" : 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: " + oe.getErrorMessage());
                System.out.println("Error Code: " + oe.getErrorCode());
                System.out.println("Request ID: " + oe.getRequestId());
            } catch (ClientException ce) {
                System.out.println("Caught a ClientException: " + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    
        // Convert bytes to a human-readable format.
        public static String formatSize(long size) {
            if (size <= 0) {
                return "0 B";
            }
            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]);
        }
    }
  • Calculate the total size of objects in a directory by using GetBucketV2 (ListObjectsV2)

    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 {
            // This example uses the endpoint for the China (Hangzhou) region. Replace it with the actual endpoint for your region.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Replace with the name of your bucket. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the region where the bucket is located. This example uses the China (Hangzhou) region.
            String region = "cn-hangzhou";
            // Specify a prefix, such as 'exampledir/'. To traverse the root directory, leave this empty.
            String prefix = "exampledir/";
    
            // Create an OSSClient instance.
            // When you no longer need the OSSClient instance, call the shutdown method to release its resources.
            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: " + (prefix.isEmpty() ? "/" : 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 a 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 to a human-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]);
        }
    }
    

References