全部產品
Search
文件中心

Object Storage Service:Java列舉檔案

更新時間:Oct 25, 2024

本文介紹如何列舉指定儲存空間下(Bucket)的所有檔案(Object)、指定個數的檔案、指定首碼的檔案等。

注意事項

背景資訊

您可以調用GetBucket(ListObjects)或GetBucketV2(ListObjectsV2)介面,一次性列舉某個Bucket下最多1000個Object。您可以通過指定參數實現多種列舉功能,例如通過指定參數列舉指定起始位置後的所有檔案、列舉指定目錄下的檔案和子目錄、以及通過分頁列舉超過1000個Object。這兩個介面的主要區別如下:

  • 使用GetBucket(ListObjects)介面列舉檔案時,預設返回owner資訊。

  • 使用GetBucketV2(ListObjectsV2)介面列舉檔案時,需通過fetchOwner指定是否在返回結果中包含owner資訊。

    說明

    對於開啟版本控制的Bucket,建議使用GetBucketV2(ListObjectsV2)介面列舉檔案。

以下分別介紹通過GetBucket(ListObjects)以及GetBucketV2(ListObjectsV2)方法列舉檔案時涉及的參數說明。

  • 通過GetBucket (ListObjects)方法列舉檔案

    GetBucket (ListObjects)有以下三類參數格式:

    • ObjectListing listObjects(String bucketName):列舉儲存空間下的檔案。單次請求預設最多列舉100個檔案。

    • ObjectListing listObjects(String bucketName, String prefix): 列舉儲存空間下指定首碼的檔案。單次請求預設最多列舉100個檔案。

    • ObjectListing listObjects(ListObjectsRequest listObjectsRequest):提供多種過濾功能,實現靈活的查詢功能。

    GetBucket (ListObjects)涉及參數說明如下:

    參數

    描述

    方法

    objectSummaries

    限定返回的檔案中繼資料。

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    本次查詢結果的首碼。

    String getPrefix()

    delimiter

    對檔案名稱進行分組的字元。

    String getDelimiter()

    marker

    標明本次列舉檔案的起點。

    String getMarker()

    maxKeys

    列舉檔案的最大個數。

    int getMaxKeys()

    nextMarker

    下一次列舉檔案的起點。

    String getNextMarker()

    isTruncated

    指明列舉檔案是否被截斷。

    • 列舉完沒有截斷,傳回值為false。

    • 沒列舉完就有截斷,傳回值為true。

    boolean isTruncated()

    commonPrefixes

    以delimiter結尾,且有共同首碼的檔案集合。

    List<String> getCommonPrefixes()

    encodingType

    指明返回結果中編碼使用的類型。

    String getEncodingType()

  • 通過GetBucketV2 (ListObjectsV2)方法列舉檔案

    GetBucketV2 (ListObjectsV2)有以下三類參數格式:

    • ListObjectsV2Result listObjectsV2(String bucketName):列舉儲存空間下的檔案。單次請求預設最多列舉100個檔案。

    • ListObjectsV2Result listObjectsV2(String bucketName, String prefix): 列舉儲存空間下指定首碼的檔案。單次請求預設最多列舉100個檔案。

    • ListObjectsV2Result listObjectsV2(ListObjectsRequest listObjectsRequest):提供多種過濾功能,實現靈活的查詢功能。

    GetBucketV2 (ListObjectsV2)涉及參數說明如下:

    參數

    描述

    方法

    objectSummaries

    限定返回的檔案中繼資料。

    List<OSSObjectSummary> getObjectSummaries()

    prefix

    本次查詢結果的首碼。

    String getPrefix()

    delimiter

    對檔案名稱進行分組的字元。

    String getDelimiter()

    startAfter

    此次列舉檔案的起點。

    String getStartAfter()

    maxKeys

    列舉檔案的最大個數。

    int getMaxKeys()

    continuationToken

    標明本次列舉檔案的起點。

    String getContinuationToken()

    nextContinuationToken

    下一次列舉檔案的起點。

    String getNextContinuationToken()

    isTruncated

    指明列舉檔案是否被截斷。

    • 列舉完沒有截斷,傳回值為false。

    • 沒列舉完就有截斷,傳回值為true。

    boolean isTruncated()

    commonPrefixes

    以delimiter結尾,且有共同首碼的檔案集合。

    List<String> getCommonPrefixes()

    encodingType

    指明返回結果中編碼使用的類型。

    String getEncodingType()

    fetchOwner

    指定是否在返回結果中包含owner資訊。

    • true:表示返回結果中包含owner資訊。

    • false:表示返回結果中不包含owner資訊。

    String getFetchOwner()

簡單列舉檔案

您可以通過GetBucket (ListObjects)方法列舉或GetBucketV2 (ListObjectsV2)方法列舉指定儲存空間下的檔案。

通過GetBucket (ListObjects)方法

以下代碼用於通過GetBucket (ListObjects)方法列舉指定儲存空間下的檔案,預設列舉100個檔案。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定首碼,例如exampledir/object。
        String keyPrefix = "exampledir/object";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 列舉檔案。如果不設定keyPrefix,則列舉儲存空間下的所有檔案。如果設定keyPrefix,則列舉包含指定首碼的檔案。
            ObjectListing objectListing = ossClient.listObjects(bucketName, keyPrefix);
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                  

通過GetBucketV2 (ListObjectsV2)方法

以下代碼用於通過GetBucketV2 (ListObjectsV2)方法列舉指定儲存空間下的檔案,預設列舉100個檔案。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定首碼,例如exampledir/object。
        String keyPrefix = "exampledir/object";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 列舉檔案。如果不設定keyPrefix,則列舉儲存空間下的所有檔案。如果設定keyPrefix,則列舉包含指定首碼的檔案。
            ListObjectsV2Result result = ossClient.listObjectsV2(bucketName, keyPrefix);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

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

通過ListObjectsRequest列舉檔案

通過設定ListObjectsRequest的參數實現各種靈活的查詢功能。ListObjectsRequest的參數如下:

參數

描述

方法

prefix

限定返回的檔案必須以prefix作為首碼。

setPrefix(String prefix)

delimiter

用於對對象(Object)名稱進行分組。通過指定一個字元(例如 /),將對象名稱按照指定字元的首次出現位置進行分組,產生具有公用首碼的對象集合。當對象名稱包含指定的 delimiter 字元時,從名稱首碼起的所有對象分組到首次出現該字元的位置。delimiter 可以協助您對對象進行分層管理和查詢,使查詢結果更加有組織和便於理解。

setDelimiter(String delimiter)

marker

列舉指定marker之後的檔案。指定該參數後,以marker為起點按檔案名稱的字母排序返迴文件。

setMarker(String marker)

maxKeys

限定此次列舉檔案的最大個數。指定該參數後,按檔案名稱的字母排序返回結果。預設值為100,最大值為1000。

setMaxKeys(Integer maxKeys)

encodingType

請求響應體中檔案名稱採用的編碼方式,目前僅支援URL。

setEncodingType(String encodingType)

列舉指定個數的檔案

以下代碼用於列舉指定個數的檔案。

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

public class Demo {
    public static void main(String[] args){
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 設定最大個數。
            final int maxKeys = 200;
            // 列舉檔案。
            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();
            }
        }
    }
}                    

列舉指定首碼的檔案

以下代碼用於列舉包含指定首碼(prefix)的檔案。

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

public class Demo {
    public static void main(String[] args){
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定首碼,例如exampledir/object。
        String keyPrefix = "exampledir/object";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 列舉包含指定首碼的檔案。預設列舉100個檔案。
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withPrefix(keyPrefix));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}                    

列舉指定marker之後的檔案

以下代碼用於列舉檔案名稱字典序中排在指定字串marker之後的檔案。

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

public class Demo {
    public static void main(String[] args){
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 設定從marker之後按字母排序開始返回Object。  
        String marker = "ex";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 列舉指定marker之後的檔案。預設列舉100個檔案。
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(marker));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

分頁列舉所有檔案

以下代碼用於分頁列舉指定儲存空間下的所有檔案。每頁列舉的檔案個數通過maxKeys指定。

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

public class Demo {
    public static void main(String[] args){
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 設定每頁列舉200個檔案。
        int maxKeys = 200;
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String nextMarker = null;
            ObjectListing objectListing;

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

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

                nextMarker = objectListing.getNextMarker();

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

分頁列舉指定首碼的檔案

以下代碼用於分頁列舉包含指定首碼的檔案。

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

public class Demo {
    public static void main(String[] args){
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定每頁列舉200個檔案。
        int maxKeys = 200;
        // 指定首碼,例如exampledir/object。
        String keyPrefix = "exampledir/object";
        // 設定marker,例如objecttest.txt。
        String nextMarker = "objecttest.txt";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        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();
            }
        }
    }
}

指定檔案名稱編碼

如果檔案名稱含有以下特殊字元,需要進行編碼傳輸。OSS目前僅支援URL編碼。

  • 單引號(' ')

  • 雙引號(" ")

  • and符號(&)

  • 角括弧(< >)

  • 頓號(、)

  • 中文

以下代碼用於指定檔案名稱編碼。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定每頁列舉200個檔案。
        int maxKeys = 200;
        // 指定首碼,例如exampledir/object。
        String keyPrefix = "exampledir/object";
        // 設定marker,例如objecttest.txt。
        String nextMarker = "objecttest.txt";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        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);

                // 指定檔案名稱編碼。
                listObjectsRequest.setEncodingType("url");

                objectListing = ossClient.listObjects(listObjectsRequest);

                // 檔案解碼。
                for (OSSObjectSummary objectSummary: objectListing.getObjectSummaries()) {
                    System.out.println("Key:" + URLDecoder.decode(objectSummary.getKey(), "UTF-8"));
                }

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

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

通過ListObjectsV2Request列舉檔案

通過設定ListObjectsV2Request參數實現靈活的列舉檔案功能,例如列舉指定個數的檔案、指定首碼(prefix)的檔案、分頁列舉所有檔案等。

ListObjectsV2Request參數說明如下:

參數

描述

方法

prefix

限定返回的檔案必須以prefix作為首碼。

setPrefix(String prefix)

delimiter

用於對對象(Object)名稱進行分組。通過指定一個字元(例如 /),將對象名稱按照指定字元的首次出現位置進行分組,產生具有公用首碼的對象集合。當對象名稱包含指定的 delimiter 字元時,從名稱首碼起的所有對象分組到首次出現該字元的位置。delimiter 可以協助您對對象進行分層管理和查詢,使查詢結果更加有組織和便於理解。

setDelimiter(String delimiter)

maxKeys

限定此次列舉檔案的最大個數。指定該參數後,按檔案名稱的字母排序返回結果。預設值為100,最大值為1000。

setMaxKeys(Integer maxKeys)

startAfter

此次列舉檔案的起點。指定該參數後,以startAfter為起點按檔案名稱的字母排序返迴文件。

setStartAfter(String startAfter)

continuationToken

此次列舉檔案使用的continuationToken。

setContinuationToken(String continuationToken)

encodingType

請求響應體中檔案名稱採用的編碼方式,目前僅支援URL。

setEncodingType(String encodingType)

fetchOwner

本次列舉結果中是否包含檔案的owner的資訊。

setFetchOwner(boolean fetchOwner )

列舉指定個數的檔案

以下代碼用於列舉指定個數的檔案。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 設定最大個數。
        int maxKeys = 200;
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 列舉檔案,每次請求預設返回100個檔案,此次指定設定最多返迴文件數為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();
            }
        }
    }
}

列舉指定首碼的檔案

以下代碼用於列舉包含指定首碼(prefix)的檔案。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定首碼,例如exampledir/object。
        String prefix = "exampledir/object";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 列舉指定首碼的檔案。
            ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
            listObjectsV2Request.setPrefix(prefix);
            ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

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

列舉指定startAfter之後的檔案

以下代碼用於列舉檔案名稱字典序中排在指定字串startAfter之後的檔案。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 設定從start-after之後按字母排序開始返回Object。          
            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();
            }
        }
    }
}

列舉結果中返迴文件的owner資訊

以下代碼用於列舉結果中返迴文件的owner資訊。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 預設列舉的檔案資訊中不包含owner資訊。如果需要包含owner資訊,請將fetchOwner參數設定為true。
            ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
            listObjectsV2Request.setFetchOwner(true);
            ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
            List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();

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

分頁列舉所有檔案

以下代碼用於分頁列舉指定儲存空間下的所有檔案。每頁列舉的檔案個數通過maxKeys指定。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 設定最大個數。
        int maxKeys = 200;
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        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;

            // 分頁列舉,每次傳入上次返回結果中的nextContinuationToken。
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);

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

                nextContinuationToken = result.getNextContinuationToken();

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

分頁列舉指定首碼的檔案

以下代碼用於分頁列舉包含指定首碼的檔案。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定首碼,例如exampledir/object。
        String keyPrefix = "exampledir/object";
        // 設定最大個數。
        int maxKeys = 200;
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        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;

            // 分頁列舉指定首碼的檔案。
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setPrefix(keyPrefix);
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);

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

                nextContinuationToken = result.getNextContinuationToken();

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

指定檔案名稱編碼

以下代碼用於指定檔案名稱編碼。

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定首碼,例如exampledir/object。
        String keyPrefix = "exampledir/object";
        // 設定最大個數。
        int maxKeys = 200;
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        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;

            // 指定返回結果使用URL編碼,則您需要對結果中的prefix、delemiter、startAfter、key和commonPrefix進行URL解碼。
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setPrefix(keyPrefix);
                listObjectsV2Request.setEncodingType("url");
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);

                // prefix解碼。
                if (result.getPrefix() != null) {
                    String prefix = URLDecoder.decode(result.getPrefix(), "UTF-8");
                    System.out.println("prefix: " + prefix);
                }

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

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

                // 檔案名稱解碼。
                for (OSSObjectSummary s : result.getObjectSummaries()) {
                    String decodedKey = URLDecoder.decode(s.getKey(), "UTF-8");
                    System.out.println("key: " + decodedKey);
                }

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

檔案夾功能

OSS沒有檔案夾的概念,所有元素都是以檔案來儲存。建立檔案夾本質上來說是建立了一個大小為0並以正斜線(/)結尾的檔案。這個檔案可以被上傳和下載,控制台會對以正斜線(/)結尾的檔案以檔案夾的方式展示。關於建立檔案夾的完整範例程式碼,請參見GitHub樣本

通過delimiter和prefix兩個參數可以類比檔案夾功能:

  • 如果設定prefix為某個檔案夾名稱,則會列舉以此prefix開頭的檔案,即該檔案夾下所有的檔案和子檔案夾(目錄)均顯示為objects。

  • 如果在設定了prefix的情況下,將delimiter設定為正斜線(/),則只列舉該檔案夾下的檔案和子檔案夾(目錄),該檔案夾下的子檔案夾(目錄)顯示為CommonPrefixes,子檔案夾下的檔案和檔案夾不顯示。

假設儲存空間中包含檔案oss.jpgfun/test.jpgfun/movie/001.avifun/movie/007.avi,以正斜線(/)作為檔案夾的分隔字元。以下樣本說明了如何通過類比檔案夾的方式列舉檔案。

列舉儲存空間下的所有檔案

  • 通過GetBucket (ListObjects)列舉儲存空間下的所有檔案

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 構造ListObjectsRequest請求。
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
    
                // 列舉檔案。
                ObjectListing listing = ossClient.listObjects(listObjectsRequest);
    
                // 遍曆所有檔案。
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // 遍曆所有commonPrefix。
                System.out.println("CommonPrefixes:");
                for (String commonPrefix : listing.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 通過GetBucketV2 (ListObjectsV2)列舉指定儲存空間下的所有檔案

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 列舉檔案。
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // 遍曆檔案。
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // 遍曆commonPrefix。
                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();
                }
            }
        }
    }
  • 返回結果

    通過以上兩種方法列舉指定儲存空間下所有檔案的返回結果如下。

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

列舉指定目錄下所有檔案

  • 通過GetBucket (ListObjects)方法列舉指定目錄下的所有檔案

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 構造ListObjectsRequest請求。
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
                // 設定prefix參數來擷取fun目錄下的所有檔案。
                listObjectsRequest.setPrefix("fun/");
    
                // 遞迴列舉fun目錄下的所有檔案。
                ObjectListing listing = ossClient.listObjects(listObjectsRequest);
    
                // 遍曆所有檔案。
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // 遍曆所有commonPrefix。
                System.out.println("\nCommonPrefixes:");
                for (String commonPrefix : listing.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 通過GetBucketV2 (ListObjectsV2)方法列舉指定目錄下所有檔案

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 構造ListObjectsV2Request請求。
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // 設定prefix參數來擷取fun目錄下的檔案。
                listObjectsV2Request.setPrefix("fun/");
    
                // 發起列舉請求。
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // 遍曆檔案。
                System.out.println("Objects:");
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // 遍曆commonPrefix。
                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();
                }
            }
        }
    }
  • 通過以上兩種方法列舉指定目錄下所有檔案的返回結果如下。

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

列舉目錄下的檔案和子目錄

  • 通過GetBucket (ListObjects)方法列舉目錄下的檔案和子目錄

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 構造ListObjectsRequest請求。
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
    
                // 設定正斜線(/)為檔案夾的分隔字元。
                listObjectsRequest.setDelimiter("/");
    
                // 列出fun目錄下的所有檔案和檔案夾。
                listObjectsRequest.setPrefix("fun/");
    
                ObjectListing listing = ossClient.listObjects(listObjectsRequest);
    
                // 遍曆所有檔案。
                System.out.println("Objects:");
                // objectSummaries的列表中給出的是fun目錄下的檔案。
                for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // 遍曆所有commonPrefix。
                System.out.println("\nCommonPrefixes:");
                // commonPrefixs列表中顯示的是fun目錄下的所有子檔案夾。由於fun/movie/001.avi和fun/movie/007.avi屬於fun檔案夾下的movie目錄,因此這兩個檔案未在列表中。
                for (String commonPrefix : listing.getCommonPrefixes()) {
                    System.out.println(commonPrefix);
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 通過GetBucketV2 (ListObjectsV2)方法列舉目錄下的檔案和子目錄

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 構造ListObjectsV2Request請求。
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
    
                // 設定prefix參數來擷取fun目錄下的所有檔案與檔案夾。
                listObjectsV2Request.setPrefix("fun/");
    
                // 設定正斜線(/)為檔案夾的分隔字元。
                listObjectsV2Request.setDelimiter("/");
    
                // 發起列舉請求。
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
    
                // 遍曆檔案。
                System.out.println("Objects:");
                // objectSummaries的列表中給出的是fun目錄下的檔案。
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                    System.out.println(objectSummary.getKey());
                }
    
                // 遍曆commonPrefix。
                System.out.println("\nCommonPrefixes:");
                // commonPrefixs列表中顯示的是fun目錄下的所有子檔案夾。由於fun/movie/001.avi和fun/movie/007.avi屬於fun檔案夾下的movie目錄,因此這兩個檔案未在列表中。
                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();
                }
            }
        }
    }
  • 通過以上兩種方法列舉指定目錄下的檔案和子目錄的返回結果如下:

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

擷取指定目錄下的檔案大小

  • 通過GetBucket (ListObjects)方法擷取指定目錄下的檔案大小

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 指定首碼,例如exampledir/object。如果您希望遍曆主目錄下的檔案夾,則將此值置空。
            String keyPrefix = "exampledir/object";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build(););
    
            try {
                ObjectListing objectListing = null;
                do {
                    // 預設情況下,每次列舉100個檔案或目錄。
                    ListObjectsRequest request = new ListObjectsRequest(bucketName).withDelimiter("/").withPrefix(keyPrefix);
                    if (objectListing != null) {
                        request.setMarker(objectListing.getNextMarker());
                    }
                    objectListing = ossClient.listObjects(request);
                    List<String> folders = objectListing.getCommonPrefixes();
                    for (String folder : folders) {
                        System.out.println(folder + " : " + (calculateFolderLength(ossClient, bucketName, folder) / 1024) + "KB");
                    }
                    List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                    for (OSSObjectSummary s : sums) {
                        System.out.println(s.getKey() + " : " + (s.getSize() / 1024) + "KB");
                    }
                } while (objectListing.isTruncated());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    
        // 擷取某個儲存空間下指定目錄(檔案夾)下的檔案大小。
        private static long calculateFolderLength(OSS ossClient, String bucketName, String folder) {
            long size = 0L;
            ObjectListing objectListing = null;
            do {
                // MaxKey預設值為100,最大值為1000。
                ListObjectsRequest request = new ListObjectsRequest(bucketName).withPrefix(folder).withMaxKeys(1000);
                if (objectListing != null) {
                    request.setMarker(objectListing.getNextMarker());
                }
                objectListing = ossClient.listObjects(request);
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    size += s.getSize();
                }
            } while (objectListing.isTruncated());
            return size;
        }
    }
  • 通過GetBucketV2 (ListObjectsV2)方法擷取指定目錄下的檔案大小

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 指定首碼,例如exampledir/object。如果您希望遍曆主目錄下的檔案夾,將該值置空。
            String keyPrefix = "exampledir/object";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                ListObjectsV2Result result = null;
                do {
                    // 預設情況下,每次列舉100個檔案或目錄。
                    ListObjectsV2Request request = new ListObjectsV2Request(bucketName).withDelimiter("/").withPrefix(keyPrefix);
                    if (result != null) {
                        request.setContinuationToken(result.getNextContinuationToken());
                    }
                    result = ossClient.listObjectsV2(request);
                    List<String> folders = result.getCommonPrefixes();
                    for (String folder : folders) {
                        System.out.println(folder + " : " + (calculateFolderLength(ossClient, bucketName, folder) / 1024) + "KB");
                    }
                    List<OSSObjectSummary> sums = result.getObjectSummaries();
                    for (OSSObjectSummary s : sums) {
                        System.out.println(s.getKey() + " : " + (s.getSize() / 1024) + "KB");
                    }
                } while (result.isTruncated());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    
        // 擷取某個儲存空間下指定目錄(檔案夾)下的檔案大小。
        private static long calculateFolderLength(OSS ossClient, String bucketName, String folder) {
            long size = 0L;
            ListObjectsV2Result result = null;
            do {
                // MaxKey預設值為100,最大值為1000。
                ListObjectsV2Request request = new ListObjectsV2Request(bucketName).withPrefix(folder).withMaxKeys(1000);
                if (result != null) {
                    request.setContinuationToken(result.getNextContinuationToken());
                }
                result = ossClient.listObjectsV2(request);
                List<OSSObjectSummary> sums = result.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    size += s.getSize();
                }
            } while (result.isTruncated());
            return size;
        }
    }

相關文檔