All Products
Search
Document Center

Object Storage Service:List objects (Java SDK V1)

Last Updated:Nov 26, 2025

This topic describes how to list all objects, a specific number of objects, and objects whose names contain a specific prefix in an Object Storage Service (OSS) bucket.

Usage 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 OSS regions and endpoints.

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

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Configuration examples for common scenarios.

  • To list objects, you must have the oss:ListObjects permission. For more information, see Grant custom permissions to a RAM user.

Background information

You can call the GetBucket (ListObjects) or GetBucketV2 (ListObjectsV2) API operation to list up to 1,000 objects in a bucket at a time. You can specify parameters to enable various listing features, such as listing all objects after a specified start position, listing files and subdirectories in a specified directory, and listing more than 1,000 objects using paging. The main differences between these two API operations are as follows:

  • When you use the GetBucket (ListObjects) API operation to list objects, owner information is returned by default.

  • When you use the GetBucketV2 (ListObjectsV2) API operation to list objects, you must use the fetchOwner parameter to specify whether to include owner information in the response.

    Note

    For buckets with versioning enabled, use the GetBucketV2 (ListObjectsV2) API operation to list objects.

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

  • List objects using the GetBucket (ListObjects) method

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

    • ObjectListing listObjects(String bucketName): lists all objects in a bucket. By default, a single request can list up to 100 objects.

    • ObjectListing listObjects(String bucketName, String prefix): lists objects whose names contain a specific prefix in a bucket. By default, a single request can list up to 100 objects.

    • ObjectListing listObjects(ListObjectsRequest listObjectsRequest): provides various filtering features for flexible queries.

    The following table describes the parameters that you can specify when you call the GetBucket (ListObjects) operation.

    Parameter

    Description

    Method

    objectSummaries

    The metadata of the objects to return.

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    The prefix of the query results.

    String getPrefix()

    delimiter

    The character used to group object names.

    String getDelimiter()

    marker

    The position from which the listing begins.

    String getMarker()

    maxKeys

    The maximum number of objects to list.

    int getMaxKeys()

    nextMarker

    The position from which the next listing begins.

    String getNextMarker()

    isTruncated

    Indicates whether the object listing is truncated.

    • false: The listing is not truncated.

    • true: The listing is truncated.

    boolean isTruncated()

    commonPrefixes

    A collection of objects whose names end with the delimiter and share a common prefix.

    List<String> getCommonPrefixes()

    encodingType

    The encoding type used in the response.

    String getEncodingType()

  • List objects using the GetBucketV2 (ListObjectsV2) method

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

    • ListObjectsV2Result listObjectsV2(String bucketName): lists all objects in a bucket. By default, a single request can list up to 100 objects.

    • ListObjectsV2Result listObjectsV2(String bucketName, String prefix): lists objects whose names contain a specific prefix in a bucket. By default, a single request can list up to 100 objects.

    • ListObjectsV2Result listObjectsV2(ListObjectsRequest listObjectsRequest): provides various filtering features for flexible queries.

    The following table describes the parameters that you can specify when you call the GetBucketV2 (ListObjectsV2) operation.

    Parameter

    Description

    Method

    objectSummaries

    The metadata of the objects to return.

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    The prefix of the query results.

    String getPrefix()

    delimiter

    The character used to group object names.

    String getDelimiter()

    startAfter

    The position from which the listing begins.

    String getStartAfter()

    maxKeys

    The maximum number of objects to list.

    int getMaxKeys()

    continuationToken

    The position from which the listing begins.

    String getContinuationToken()

    nextContinuationToken

    The position from which the next listing begins.

    String getNextContinuationToken()

    isTruncated

    Indicates whether the object listing is truncated.

    • false: The listing is not truncated.

    • true: The listing is truncated.

    boolean isTruncated()

    commonPrefixes

    A collection of objects whose names end with the delimiter and share a common prefix.

    List<String> getCommonPrefixes()

    encodingType

    The encoding type used in the response.

    String getEncodingType()

    fetchOwner

    Specifies whether to include owner information in the response.

    • true: The response includes the owner information.

    • false: The response does not include the owner information.

    String getFetchOwner()

Simple object listing

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

Using the GetBucket (ListObjects) method

The following sample code provides an example of how to use the GetBucket (ListObjects) method to list objects in a specific bucket. By default, a 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify a prefix, such as exampledir/object.
        String keyPrefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 you do not set keyPrefix, all objects in the bucket are listed. If you set keyPrefix, objects whose names contain the specified prefix are listed.
            ObjectListing objectListing = ossClient.listObjects(bucketName, keyPrefix);
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                  

Using the GetBucketV2 (ListObjectsV2) method

The following sample code provides an example of how to use the GetBucketV2 (ListObjectsV2) method to list objects in a specific bucket. By default, a 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify a prefix, such as exampledir/object.
        String keyPrefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 you do not set keyPrefix, all objects in the bucket are listed. If you set keyPrefix, objects whose names contain the specified prefix are listed.
            ListObjectsV2Result result = ossClient.listObjectsV2(bucketName, keyPrefix);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

            for (OSSObjectSummary s : ossObjectSummaries) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

List objects using ListObjectsRequest

You can set the parameters of ListObjectsRequest to enable various flexible query features. The following table describes the parameters of ListObjectsRequest.

Parameter

Description

Method

prefix

The prefix that the names of returned objects must contain.

setPrefix(String prefix)

delimiter

A character used to group object names. All object names that contain the same string from the prefix to the first occurrence of the delimiter are grouped as a single result element under CommonPrefixes. This helps you traverse the bucket as a folder hierarchy.

setDelimiter(String delimiter)

marker

The object name after which the listing begins. This parameter returns objects whose names are sorted in lexicographical order after the value of marker.

setMarker(String marker)

maxKeys

The maximum number of objects to return. The results are returned in lexicographical order. The default value is 100. The maximum value is 1,000.

setMaxKeys(Integer maxKeys)

encodingType

The encoding type for object names in the response body. Only URL encoding is supported.

setEncodingType(String encodingType)

List a specific number of objects

The following sample code provides an example of 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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.
            final int maxKeys = 200;
            // List objects.
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                    

List objects with a specific prefix

The following sample code provides an example of how to list objects that contain a specific 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify a prefix, such as exampledir/object.
        String keyPrefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 contain the specified prefix. By default, 100 objects are listed.
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withPrefix(keyPrefix));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                    

List objects after a specified marker

The following sample code provides an example of how to list objects whose names are lexicographically after a specified string 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify that objects are returned in alphabetical order starting from the object that follows the marker.  
        String marker = "ex";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 listed.
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(marker));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

List all objects by page

The following sample code provides an example of how to list all objects in a specific bucket by page. The number of objects to list on each page is specified by the maxKeys 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 {
        // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Set the number of objects to list on each page to 200.
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 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 specific prefix by page

The following sample code provides an example of how to list objects that contain a specific 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 {
        // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify the number of objects to list on each page as 200.
        int maxKeys = 200;
        // Specify a prefix, such as exampledir/object.
        String keyPrefix = "exampledir/object";
        // Set a marker, such as objecttest.txt.
        String nextMarker = "objecttest.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 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 name encoding

If an object name contains the following special characters, you must encode the name for transmission. OSS supports only URL encoding.

  • Single quotation marks (' ')

  • Double quotation marks (" ")

  • Ampersands (&)

  • Angle brackets (< >)

  • Enumeration comma (、)

  • Chinese

The following sample code provides an example of how to specify the encoding of 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify the number of objects to list on each page as 200.
        int maxKeys = 200;
        // Specify a prefix, such as exampledir/object.
        String keyPrefix = "exampledir/object";
        // Set a marker, such as objecttest.txt.
        String nextMarker = "objecttest.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 {
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
                listObjectsRequest.setPrefix(keyPrefix);
                listObjectsRequest.setMaxKeys(maxKeys);
                listObjectsRequest.setMarker(nextMarker);

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

                objectListing = ossClient.listObjects(listObjectsRequest);

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

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

                // Decode nextMarker.
                if (objectListing.getNextMarker() != null) {
                    nextMarker = URLDecoder.decode(objectListing.getNextMarker(), "UTF-8");
                }
            } while (objectListing.isTruncated());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

List objects using ListObjectsV2Request

You can set the parameters of ListObjectsV2Request to enable flexible object listing features, such as listing a specific number of objects, listing objects with a specific prefix, and listing all objects by page.

The following table describes the parameters of ListObjectsV2Request.

Parameter

Description

Method

prefix

The prefix that the names of returned objects must contain.

setPrefix(String prefix)

delimiter

A character used to group object names. All object names that contain the same string from the prefix to the first occurrence of the delimiter are grouped as a single result element under CommonPrefixes. This helps you traverse the bucket as a folder hierarchy.

setDelimiter(String delimiter)

maxKeys

The maximum number of objects to return. The results are returned in lexicographical order. The default value is 100. The maximum value is 1,000.

setMaxKeys(Integer maxKeys)

startAfter

The object name after which the listing begins. This parameter returns objects whose names are sorted in lexicographical order after the value of startAfter.

setStartAfter(String startAfter)

continuationToken

The continuationToken used for this listing operation.

setContinuationToken(String continuationToken)

encodingType

The encoding type for object names in the response body. Only URL encoding is supported.

setEncodingType(String encodingType)

fetchOwner

Specifies whether to include the owner information of the objects in the listing results.

setFetchOwner(boolean fetchOwner )

List a specific number of objects

The following sample code provides an example of 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Set the maximum number of objects.
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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, 100 objects are returned by a single request. In this example, the maximum number of objects to return is set 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 specific prefix

The following sample code provides an example of how to list objects that contain a specific 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify a prefix, such as exampledir/object.
        String prefix = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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.
            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 after a specified startAfter value

The following sample code provides an example of how to list objects whose names are lexicographically after a specified string startAfter.

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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Specify that objects are returned in alphabetical order starting from the object that follows start-after.          
            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();
            }
        }
    }
}

Return owner information in the listing results

The following sample code provides an example of how to return owner information in the listing 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 {
        // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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, the listed object information does not include owner information. To include owner information, 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 sample code provides an example of how to list all objects in a specific bucket by page. The number of objects to list on each page is specified by the maxKeys 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 {
        // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Set the maximum number of objects.
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 value from the previous response.
            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 specific prefix by page

The following sample code provides an example of how to list objects that contain a specific 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 {
        // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify a prefix, such as exampledir/object.
        String keyPrefix = "exampledir/object";
        // Set the maximum number of objects.
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 with 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 name encoding

The following sample code provides an example of how to specify the encoding of 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 of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
        String bucketName = "examplebucket";
        // Specify a prefix, such as exampledir/object.
        String keyPrefix = "exampledir/object";
        // Set the maximum number of objects.
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 returned results are URL-encoded, you must URL-decode the prefix, delimiter, startAfter, key, and commonPrefix values in the results.
            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 startAfter.
                if (result.getStartAfter() != null) {
                    String startAfter = URLDecoder.decode(result.getStartAfter(), "UTF-8");
                    System.out.println("startAfter: " + startAfter);
                }

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

                // Decode commonPrefixes.
                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();
            }
        }
    }
}

Folder feature

OSS uses a flat structure to store objects. All elements are stored as objects. Creating a folder is equivalent to creating a zero-byte object that ends with a forward slash (/). The OSS console displays an object whose name ends with a forward slash (/) as a folder. For the complete sample code for creating a folder, see the GitHub example.

You can use the delimiter and prefix parameters to simulate a directory feature:

  • If you set the `prefix` parameter to a folder name, objects whose names start with this prefix are listed. This recursively lists all objects and subdirectories within the folder.

  • If you set the `prefix` parameter and set the `delimiter` parameter to a forward slash (/), only the objects and subdirectories at the top level of the folder are listed. The subdirectories are returned in the `CommonPrefixes` element, and the objects and folders within those subdirectories are not listed.

Assume that a bucket contains the objects oss.jpg, fun/test.jpg, fun/movie/001.avi, and fun/movie/007.avi, and the folder separator is a forward slash (/). The following examples show how to list objects by simulating directories.

List all objects in a bucket

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

    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 of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Construct a ListObjectsRequest request.
                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 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 in a bucket using the GetBucketV2 (ListObjectsV2) method

    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 of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release 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 the objects.
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse the 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 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();
                }
            }
        }
    }
  • Response

    The following response is returned by the two preceding methods.

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

List all objects in a specific directory

  • List all objects in a specific directory using the GetBucket (ListObjects) method

    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 of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Construct a ListObjectsRequest request.
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
                // Set the prefix parameter to obtain 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 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 in a specific directory using the GetBucketV2 (ListObjectsV2) method

    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 of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Construct a ListObjectsV2Request request.
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // Set the prefix parameter to obtain objects in the fun directory.
                listObjectsV2Request.setPrefix("fun/");
    
                // Initiate the listing request.
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // Traverse the objects.
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse the 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 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();
                }
            }
        }
    }
  • The following response is returned by the two preceding methods.

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

List objects and subdirectories in a directory

  • List objects and subdirectories in a directory using the GetBucket (ListObjects) method

    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 of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Construct a ListObjectsRequest request.
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
    
                // Set the folder separator to a forward slash (/).
                listObjectsRequest.setDelimiter("/");
    
                // List all objects and folders in the fun directory.
                listObjectsRequest.setPrefix("fun/");
    
                ObjectListing listing = ossClient.listObjects(listObjectsRequest);
    
                // Traverse all objects.
                System.out.println("Objects:");
                // The objectSummaries list contains the objects in the fun directory.
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse all common prefixes.
                System.out.println("\nCommonPrefixes:");
                // The commonPrefixes list shows all subdirectories in the fun directory. The fun/movie/001.avi and fun/movie/007.avi objects are not in the list because they are in the movie directory under the fun folder.
                for (String commonPrefix : listing.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • List objects and subdirectories in a directory using the GetBucketV2 (ListObjectsV2) method

    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 of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is 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 used, call the shutdown method to release resources.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Construct a ListObjectsV2Request request.
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // Set the prefix parameter to obtain all objects and folders in the fun directory.
                listObjectsV2Request.setPrefix("fun/");
    
                // Set the folder separator to a forward slash (/).
                listObjectsV2Request.setDelimiter("/");
    
                // Initiate the listing request.
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // Traverse the objects.
                System.out.println("Objects:");
                // The objectSummaries list contains the objects in the fun directory.
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // Traverse the common prefixes.
                System.out.println("\nCommonPrefixes:");
                // The commonPrefixes list shows all subdirectories in the fun directory. The fun/movie/001.avi and fun/movie/007.avi objects are not in the list because they are in the movie directory under the fun folder.
                for (String commonPrefix : result.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • The following is the output of listing the files and subdirectories in a specified directory using the two preceding methods:

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

Get the size of objects in a specific directory

  • Get the size of objects in a specific directory using the GetBucket (ListObjects) method

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.CredentialsProviderFactory;
    import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
    import com.aliyun.oss.common.comm.SignVersion;
    import com.aliyun.oss.model.OSSObjectSummary;
    import com.aliyun.oss.model.ObjectListing;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
            String region = "cn-hangzhou";
            // Specify a prefix, such as exampledir/. If you want to traverse folders in the root directory, leave this parameter empty.
            String prefix = "exampledir/";
    
            // Create an OSSClient instance.
            // When the OSSClient instance is no longer used, call the shutdown method to release 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 {
                    ObjectListing objectListing = ossClient.listObjects(bucketName, prefix);
                    for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                        totalSize += objectSummary.getSize();
                        totalCount++;
                        // Print the name and size of each file.
                        System.out.println("File: " + objectSummary.getKey() + " | Size: " + objectSummary.getSize() + " bytes (" + formatSize(objectSummary.getSize()) + ")");
                    }
                    nextMarker = objectListing.getNextMarker();
                } while (nextMarker != null && !nextMarker.isEmpty());
    
                System.out.println("Folder: " + prefix);
                System.out.println("Total objects: " + totalCount);
                System.out.println("Total size (bytes): " + totalSize);
                System.out.println("Total size (human readable): " + formatSize(totalSize));
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    
        // Convert bytes 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]);
        }
    }
    
  • Get the size of objects in a specific directory using the GetBucketV2 (ListObjectsV2) method

    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 of the China (Hangzhou) region. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this 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 bucket name, such as examplebucket.
            String bucketName = "examplebucket";
            // Specify the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
            String region = "cn-hangzhou";
            // Specify a prefix, such as exampledir/. If you want to traverse folders in the root directory, leave this parameter empty.
            String prefix = "exampledir/";
    
            // Create an OSSClient instance.
            // When the OSSClient instance is no longer used, call the shutdown method to release 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);
                System.out.println("Total objects: " + totalCount);
                System.out.println("Total size (bytes): " + totalSize);
                System.out.println("Total size (human readable): " + formatSize(totalSize));
            }catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    
        // Convert bytes 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