本文介紹如何列舉指定存儲空間下(Bucket)的所有文件(Object)、指定個數的文件、指定前綴的文件等。
注意事項
本文以華東1(杭州)外網Endpoint為例。如果您希望通過與OSS同地域的其他阿里云產品訪問OSS,請使用內網Endpoint。關于OSS支持的Region與Endpoint的對應關系,請參見OSS訪問域名、數據中心、開放端口。
本文以從環境變量讀取訪問憑證為例。如何配置訪問憑證,請參見Java配置訪問憑證。
本文以OSS域名新建OSSClient為例。如果您希望通過自定義域名、STS等方式新建OSSClient,請參見新建OSSClient。
要列舉文件,您必須有
oss:ListObjects
權限。具體操作,請參見為RAM用戶授權自定義的權限策略。
背景信息
您可以調用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.jpg
、fun/test.jpg
、fun/movie/001.avi
和fun/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; } }
相關文檔
關于列舉文件的完整示例代碼,請參見GitHub示例。
關于列舉文件的API接口說明,請參見GetBucket (ListObjects)和ListObjectsV2(GetBucketV2)。
關于列舉和管理LiveChannel相關文件的操作,請參見LiveChannel管理。