Este tópico descreve como listar todos os objetos, um número específico de objetos e objetos cujos nomes contêm um prefixo específico em um bucket do Object Storage Service (OSS).
Observações de uso
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints suportados, consulte Regiões e endpoints.
As credenciais de acesso neste exemplo são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Configuração do cliente.
Para listar objetos, é necessário ter a permissão
oss:ListObjects. Para mais informações, consulte Conceder uma política personalizada.
Informações básicas
-
GetBucket (ListObjects)
Chame a operação GetBucket (ListObjects) em um dos seguintes formatos:
ObjectListing listObjects(String bucketName): lista todos os objetos em um bucket. Por padrão, uma única solicitação lista até 100 objetos.
ObjectListing listObjects(String bucketName, String prefix): lista objetos cujos nomes contêm um prefixo específico em um bucket. Por padrão, uma única solicitação lista até 100 objetos.
ObjectListing listObjects(ListObjectsRequest listObjectsRequest): lista objetos que atendem às condições especificadas. Use este formato para listar objetos de maneira flexível.
A tabela a seguir descreve os parâmetros especificáveis ao chamar a operação GetBucket (ListObjects).
Parâmetro
Descrição
Método
objectSummaries
Metadados dos objetos a serem listados.
List<OSSObjectSummary> getObjectSummaries()
prefix
Prefixo nos nomes dos objetos a serem listados.
String getPrefix()
delimiter
Caractere usado para agrupar por nome os objetos a serem listados.
String getDelimiter()
marker
Posição inicial da operação de listagem.
String getMarker()
maxKeys
Número máximo de objetos listados por vez.
int getMaxKeys()
nextMarker
Posição inicial da próxima operação de listagem.
String getNextMarker()
isTruncated
Indica se a listagem de objetos foi truncada. Valores válidos:
-
false: Todos os objetos são listados sem truncamento.
-
true: Apenas parte dos objetos é listada.
boolean isTruncated()
commonPrefixes
Conjunto de substrings de nomes de objetos. Objetos cujos nomes terminam com o delimitador e contêm o mesmo prefixo são agrupados como um único elemento de resultado em CommonPrefixes.
List<String> getCommonPrefixes()
encodingType
Tipo de codificação dos nomes dos objetos na resposta.
String getEncodingType()
-
GetBucketV2 (ListObjectsV2)
Chame a operação GetBucketV2 (ListObjectsV2) em um dos seguintes formatos:
ListObjectsV2Result listObjectsV2(String bucketName): lista todos os objetos em um bucket. Por padrão, uma única solicitação lista até 100 objetos.
ListObjectsV2Result listObjectsV2(String bucketName, String prefix): lista objetos cujos nomes contêm um prefixo específico em um bucket. Por padrão, uma única solicitação lista até 100 objetos.
ListObjectsV2Result listObjectsV2(ListObjectsRequest listObjectsRequest): lista objetos que atendem às condições especificadas. Use este formato para listar objetos de maneira flexível.
A tabela a seguir descreve os parâmetros especificáveis ao chamar a operação GetBucketV2 (ListObjectsV2).
Parâmetro
Descrição
Método
objectSummaries
Metadados dos objetos a serem listados.
List<OSSObjectSummary> getObjectSummaries()
prefix
Prefixo nos nomes dos objetos a serem listados.
String getPrefix()
delimiter
Caractere usado para agrupar por nome os objetos a serem listados.
String getDelimiter()
startAfter
Posição inicial da operação de listagem.
String getStartAfter()
maxKeys
Número máximo de objetos listados por vez.
int getMaxKeys()
continuationToken
Posição inicial da operação de listagem.
String getContinuationToken()
nextContinuationToken
Posição inicial da próxima operação de listagem.
String getNextContinuationToken()
isTruncated
Indica se a listagem de objetos foi truncada. Valores válidos:
-
false: Todos os objetos são listados sem truncamento.
-
true: Apenas parte dos objetos é listada.
boolean isTruncated()
commonPrefixes
Conjunto de substrings de nomes de objetos. Objetos cujos nomes terminam com o delimitador e contêm o mesmo prefixo são agrupados como um único elemento de resultado em CommonPrefixes.
List<String> getCommonPrefixes()
encodingType
Tipo de codificação dos nomes dos objetos na resposta.
String getEncodingType()
fetchOwner
Indica se as informações do proprietário do objeto devem ser incluídas na resposta. Valores válidos:
-
true: A resposta inclui as informações do proprietário do objeto.
-
false: A resposta não inclui as informações do proprietário do objeto.
String getFetchOwner()
Listar objetos usando listagem simples
Chame a operação GetBucket (ListObjects) ou GetBucketV2 (ListObjectsV2) para listar objetos em um bucket específico.
Chamar a operação GetBucket (ListObjects) para listar objetos
O exemplo a seguir mostra como chamar a operação GetBucket (ListObjects) para listar objetos em um bucket específico. Por padrão, cada solicitação lista 100 objetos.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// List objects. If you do not specify keyPrefix, all objects in the bucket are listed. If you specify keyPrefix, the objects whose names contain the specified prefix are listed.
ObjectListing objectListing = ossClient.listObjects(bucketName, keyPrefix);
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Chamar a operação GetBucketV2 (ListObjectsV2) para listar objetos
O exemplo a seguir mostra como chamar a operação GetBucketV2 (ListObjectsV2) para listar objetos em um bucket específico. Por padrão, cada solicitação lista 100 objetos.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// List objects. If you do not specify keyPrefix, all objects in the bucket are listed. If you specify keyPrefix, the objects whose names contain the specified prefix are listed.
ListObjectsV2Result result = ossClient.listObjectsV2(bucketName, keyPrefix);
List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();
for (OSSObjectSummary s : ossObjectSummaries) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Chamar a operação ListObjectsRequest para listar objetos
Especifique parâmetros ao chamar a operação ListObjectsRequest para listar objetos de maneira flexível. A tabela a seguir descreve os parâmetros especificáveis ao chamar essa operação.
|
Parâmetro |
Descrição |
Método |
|
prefix |
Prefixo obrigatório nos nomes dos objetos a serem listados. |
setPrefix(String prefix) |
|
delimiter |
Caractere usado para agrupar por nome os objetos a serem listados. Por exemplo, defina o delimitador como uma barra (/). Objetos cujos nomes contêm a mesma string entre o prefixo especificado e a primeira ocorrência da barra (/) são agrupados como um elemento CommonPrefixes. Todos os objetos cujos nomes contêm os elementos CommonPrefixes são listados. Use o parâmetro delimiter para gerenciar e consultar objetos de forma hierárquica, garantindo resultados mais organizados e intuitivos. |
setDelimiter(String delimiter) |
|
marker |
Posição inicial da operação de listagem. Objetos cujos nomes estão alfabeticamente após o valor de marker são listados. |
setMarker(String marker) |
|
maxKeys |
Número máximo de objetos listados por vez. Após especificar este parâmetro, os objetos são listados em ordem alfabética. Valor máximo: 1000. Valor padrão: 100. |
setMaxKeys(Integer maxKeys) |
|
encodingType |
Tipo de codificação dos nomes dos objetos na resposta. Valor válido: URL. |
setEncodingType(String encodingType) |
Listar um número específico de objetos
O exemplo a seguir mostra como listar um número específico de objetos em um bucket:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Specify the maximum number of objects that can be listed at a time.
final int maxKeys = 200;
// List objects.
ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes contêm um prefixo específico
O exemplo a seguir mostra como listar objetos cujos nomes contêm um prefixo específico em um bucket:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// List objects whose names contain the specified prefix. By default, 100 objects are listed.
ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withPrefix(keyPrefix));
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes estão alfabeticamente após o valor de marker
O exemplo a seguir mostra como listar objetos cujos nomes estão alfabeticamente após o valor de marker:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the name of the object after which the list begins. If this parameter is specified, objects whose names are alphabetically after the value of marker are returned.
String marker = "ex";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// List objects whose names are alphabetically after the object specified by marker. By default, 100 objects are listed.
ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(marker));
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar todos os objetos em um bucket por página
O exemplo a seguir mostra como listar todos os objetos em um bucket por página. Use maxKeys para especificar o número máximo de objetos listados em cada página.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Set maxKeys to 200.
int maxKeys = 200;
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
String nextMarker = null;
ObjectListing objectListing;
do {
objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(maxKeys));
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
nextMarker = objectListing.getNextMarker();
} while (objectListing.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes contêm um prefixo específico por página
O exemplo a seguir mostra como listar objetos cujos nomes contêm um prefixo específico por página:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Set maxKeys to 200.
int maxKeys = 200;
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Specify the marker parameter. Example: objecttest.txt.
String nextMarker = "objecttest.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
ObjectListing objectListing;
do {
objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).
withPrefix(keyPrefix).withMarker(nextMarker).withMaxKeys(maxKeys));
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
nextMarker = objectListing.getNextMarker();
} while (objectListing.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes são codificados usando um tipo de codificação específico
Se o nome de um objeto contiver um dos caracteres a seguir, ele deverá ser codificado em URL antes da transmissão. O OSS suporta apenas codificação URL.
Aspas simples (')
Aspas duplas (")
E comercial (&)
Sinais de maior/menor que (<>)
Marcadores de pausa (、)
Caracteres chineses
O exemplo a seguir mostra como listar objetos cujos nomes são codificados usando um tipo de codificação específico:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.net.URLDecoder;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Set maxKeys to 200.
int maxKeys = 200;
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Specify the marker parameter. Example: objecttest.txt.
String nextMarker = "objecttest.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
ObjectListing objectListing;
do {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
listObjectsRequest.setPrefix(keyPrefix);
listObjectsRequest.setMaxKeys(maxKeys);
listObjectsRequest.setMarker(nextMarker);
// Specify the encoding type of the object names.
listObjectsRequest.setEncodingType("url");
objectListing = ossClient.listObjects(listObjectsRequest);
// Decode the values of object keys in the response.
for (OSSObjectSummary objectSummary: objectListing.getObjectSummaries()) {
System.out.println("Key:" + URLDecoder.decode(objectSummary.getKey(), "UTF-8"));
}
// Decode the value of CommonPrefixes in the response.
for (String commonPrefixes: objectListing.getCommonPrefixes()) {
System.out.println("CommonPrefixes:" + URLDecoder.decode(commonPrefixes, "UTF-8"));
}
// Decode the value of nextMarker in the response.
if (objectListing.getNextMarker() != null) {
nextMarker = URLDecoder.decode(objectListing.getNextMarker(), "UTF-8");
}
} while (objectListing.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Chamar a operação ListObjectsV2Request para listar objetos
Especifique parâmetros ao chamar a operação ListObjectsV2Request para listar objetos de maneira flexível. Por exemplo, liste um número específico de objetos, objetos cujos nomes contêm um prefixo específico ou todos os objetos em um bucket por página.
A tabela a seguir descreve os parâmetros especificáveis ao chamar a operação ListObjectsV2Request.
|
Parâmetro |
Descrição |
Método |
|
prefix |
Prefixo obrigatório nos nomes dos objetos a serem listados. |
setPrefix(String prefix) |
|
delimiter |
Caractere usado para agrupar por nome os objetos a serem listados. Por exemplo, defina o delimitador como uma barra (/). Objetos cujos nomes contêm a mesma string entre o prefixo especificado e a primeira ocorrência da barra (/) são agrupados como um elemento CommonPrefixes. Todos os objetos cujos nomes contêm os elementos CommonPrefixes são listados. Use o parâmetro delimiter para gerenciar e consultar objetos de forma hierárquica, garantindo resultados mais organizados e intuitivos. |
setDelimiter(String delimiter) |
|
maxKeys |
Número máximo de objetos listados por vez. Após especificar este parâmetro, os objetos são listados em ordem alfabética. Valor máximo: 1000. Valor padrão: 100. |
setMaxKeys(Integer maxKeys) |
|
startAfter |
Posição inicial da operação de listagem. Objetos cujos nomes estão alfabeticamente após o valor de startAfter são listados. |
setStartAfter(String startAfter) |
|
continuationToken |
ContinuationToken usado nesta operação de listagem. |
setContinuationToken(String continuationToken) |
|
encodingType |
Tipo de codificação dos nomes dos objetos na resposta. Valor válido: URL. |
setEncodingType(String encodingType) |
|
fetchOwner |
Indica se as informações do proprietário devem ser incluídas na resposta. |
setFetchOwner(boolean fetchOwner ) |
Listar um número específico de objetos
O exemplo a seguir mostra como listar um número específico de objetos em um bucket:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the maximum number of objects that can be listed at a time.
int maxKeys = 200;
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// List objects. By default, 100 objects are returned by a single request. In this example, up to 200 objects can be returned at a time.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setMaxKeys(maxKeys);
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();
for (OSSObjectSummary s : ossObjectSummaries) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes contêm um prefixo específico
O exemplo a seguir mostra como listar objetos cujos nomes contêm um prefixo específico em um bucket:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String prefix = "exampledir/object";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// List objects whose names contain the specified prefix.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setPrefix(prefix);
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();
for (OSSObjectSummary s : ossObjectSummaries) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes estão alfabeticamente após o valor de startAfter
O exemplo a seguir mostra como listar objetos cujos nomes estão alfabeticamente após o valor de startAfter:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Specify the name of the object after which the list begins. If this parameter is specified, objects whose names are alphabetically after the value of start-after are returned.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setStartAfter("ex");
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();
for (OSSObjectSummary s : ossObjectSummaries) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos e suas informações de proprietário
O exemplo a seguir mostra como listar objetos e suas informações de proprietário:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// By default, the object owner information is not listed. To include the object owner information in the response, set the fetchOwner parameter to true.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setFetchOwner(true);
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
List<OSSObjectSummary> ossObjectSummaries = result.getObjectSummaries();
for (OSSObjectSummary s : ossObjectSummaries) {
System.out.println("\t" + s.getKey());
if (s.getOwner() != null) {
System.out.println("owner id:" + s.getOwner().getId());
System.out.println("name:" + s.getOwner().getDisplayName());
}
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar todos os objetos em um bucket por página
O exemplo a seguir mostra como listar todos os objetos em um bucket por página. Use maxKeys para especificar o número máximo de objetos listados em cada página.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the maximum number of objects that can be listed at a time.
int maxKeys = 200;
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
String nextContinuationToken = null;
ListObjectsV2Result result = null;
// List objects by page by using the nextContinuationToken parameter included in the response of the previous list operation.
do {
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
listObjectsV2Request.setContinuationToken(nextContinuationToken);
result = ossClient.listObjectsV2(listObjectsV2Request);
List<OSSObjectSummary> sums = result.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
nextContinuationToken = result.getNextContinuationToken();
} while (result.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes contêm um prefixo específico por página
O exemplo a seguir mostra como listar objetos cujos nomes contêm um prefixo específico por página:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Specify the maximum number of objects that can be listed at a time.
int maxKeys = 200;
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
String nextContinuationToken = null;
ListObjectsV2Result result = null;
// List the objects whose names contain the specified prefix by page.
do {
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
listObjectsV2Request.setPrefix(keyPrefix);
listObjectsV2Request.setContinuationToken(nextContinuationToken);
result = ossClient.listObjectsV2(listObjectsV2Request);
List<OSSObjectSummary> sums = result.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
nextContinuationToken = result.getNextContinuationToken();
} while (result.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos cujos nomes são codificados usando um tipo de codificação específico
O exemplo a seguir mostra como listar objetos cujos nomes são codificados usando um tipo de codificação específico:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.net.URLDecoder;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Specify the maximum number of objects that can be listed at a time.
int maxKeys = 200;
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
String nextContinuationToken = null;
ListObjectsV2Result result = null;
// Specify that the returned results are URL-encoded. In this case, you must decode the values of the prefix, delimiter, startAfter, key, and commonPrefixes parameters in the response.
do {
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
listObjectsV2Request.setPrefix(keyPrefix);
listObjectsV2Request.setEncodingType("url");
listObjectsV2Request.setContinuationToken(nextContinuationToken);
result = ossClient.listObjectsV2(listObjectsV2Request);
// Decode the value of prefix in the response.
if (result.getPrefix() != null) {
String prefix = URLDecoder.decode(result.getPrefix(), "UTF-8");
System.out.println("prefix: " + prefix);
}
// Decode the value of delimiter in the response.
if (result.getDelimiter() != null) {
String delimiter = URLDecoder.decode(result.getDelimiter(), "UTF-8");
System.out.println("delimiter: " + delimiter);
}
// Decode the value of startAfter in the response.
if (result.getStartAfter() != null) {
String startAfter = URLDecoder.decode(result.getStartAfter(), "UTF-8");
System.out.println("startAfter: " + startAfter);
}
// Decode the values of object keys in the response.
for (OSSObjectSummary s : result.getObjectSummaries()) {
String decodedKey = URLDecoder.decode(s.getKey(), "UTF-8");
System.out.println("key: " + decodedKey);
}
// Decode the value of CommonPrefixes in the response.
for (String commonPrefix: result.getCommonPrefixes()) {
String decodeCommonPrefix = URLDecoder.decode(commonPrefix, "UTF-8");
System.out.println("CommonPrefix:" + decodeCommonPrefix);
}
nextContinuationToken = result.getNextContinuationToken();
} while (result.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Listar objetos por diretório
O OSS usa uma estrutura plana para armazenar objetos. Um diretório é um objeto de zero bytes cujo nome termina com uma barra (/). É possível fazer upload e baixe desse objeto. Por padrão, um objeto cujo nome termina com uma barra (/) é exibido como um diretório no console do OSS. Para obter o código de exemplo completo usado para crie diretórios, visite o GitHub.
Especifique os parâmetros delimiter e prefix para listar objetos por diretório.
Se você definir prefix como um nome de diretório na solicitação, os objetos e subdiretórios cujos nomes contêm o prefixo serão listados.
Se você especifique um prefixo e defina delimiter como uma barra (/) na solicitação, os objetos e subdiretórios cujos nomes começam com o prefixo especificado no diretório serão listados. Cada subdiretório é listado como um único elemento de resultado em CommonPrefixes. Os objetos e diretórios dentro desses subdiretórios não são listados.
Por exemplo, um bucket contém os seguintes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.avi. A barra (/) é especificada como o delimitador de diretório. Os exemplos a seguir descrevem como listar objetos em diretórios simulados.
Listar todos os objetos no bucket
-
O exemplo a seguir mostra como chamar a operação GetBucket (ListObjects) para listar todos os objetos no bucket:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create a request to list objects. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName); // List objects. ObjectListing listing = ossClient.listObjects(listObjectsRequest); // Traverse all objects. System.out.println("Objects:"); for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) { System.out.println(objectSummary.getKey()); } // Traverse all CommonPrefix elements. System.out.println("CommonPrefixes:"); for (String commonPrefix : listing.getCommonPrefixes()) { System.out.println(commonPrefix); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } -
O exemplo a seguir mostra como chamar a operação GetBucketV2 (ListObjectsV2) para listar todos os objetos em um bucket:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // List objects. ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName); ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request); // Traverse all objects. System.out.println("Objects:"); for (OSSObjectSummary objectSummary : result.getObjectSummaries()) { System.out.println(objectSummary.getKey()); } // Traverse all CommonPrefix elements. System.out.println("CommonPrefixes:"); for (String commonPrefix : result.getCommonPrefixes()) { System.out.println(commonPrefix); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } -
Parâmetros de resposta
Os dois métodos anteriores que listam todos os objetos em um bucket retornam a seguinte resposta:
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg oss.jpg CommonPrefixes:
Listar todos os objetos em um diretório
-
O exemplo a seguir mostra como chamar a operação GetBucket (ListObjects) para listar todos os objetos em um diretório:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create a request to list objects. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName); // Set prefix to fun/ to list all objects in the fun/ directory. listObjectsRequest.setPrefix("fun/"); // Lists all objects in the fun/ directory. ObjectListing listing = ossClient.listObjects(listObjectsRequest); // Traverse all objects. System.out.println("Objects:"); for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) { System.out.println(objectSummary.getKey()); } // Traverse all CommonPrefix elements. System.out.println("\nCommonPrefixes:"); for (String commonPrefix : listing.getCommonPrefixes()) { System.out.println(commonPrefix); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } -
O exemplo a seguir mostra como chamar a operação GetBucketV2 (ListObjectsV2) para listar todos os objetos em um diretório específico:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create a ListObjectsV2Request request to list objects. ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName); // Set prefix to fun/ to list all objects in the fun/ directory. listObjectsV2Request.setPrefix("fun/"); // Initiate the request. ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request); // Traverse all objects. System.out.println("Objects:"); for (OSSObjectSummary objectSummary : result.getObjectSummaries()) { System.out.println(objectSummary.getKey()); } // Traverse all CommonPrefix elements. System.out.println("\nCommonPrefixes:"); for (String commonPrefix : result.getCommonPrefixes()) { System.out.println(commonPrefix); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } -
As duas operações anteriores que listam todos os objetos no diretório especificado retornam a seguinte resposta:
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg CommonPrefixes:
Listar objetos e subdiretórios em um diretório específico
-
O exemplo a seguir mostra como chamar a operação GetBucket (ListObjects) para listar objetos e subdiretórios em um diretório específico:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create a request to list objects. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName); // Set the delimiter to a forward slash (/). listObjectsRequest.setDelimiter("/"); // List all objects and subdirectories in the fun/ directory. listObjectsRequest.setPrefix("fun/"); ObjectListing listing = ossClient.listObjects(listObjectsRequest); // Traverse all objects. System.out.println("Objects:"); // In the response, objectSummaries lists the objects in the fun/ directory. for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) { System.out.println(objectSummary.getKey()); } // Traverse all CommonPrefix elements. System.out.println("\nCommonPrefixes:"); // CommonPrefixs lists all subdirectories in the fun/ directory. The fun/movie/001.avi and fun/movie/007.avi objects are not listed because they are in the movie/ subdirectory of the fun/ directory. for (String commonPrefix : listing.getCommonPrefixes()) { System.out.println(commonPrefix); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } -
O exemplo a seguir mostra como chamar a operação GetBucketV2 (ListObjectsV2) para listar objetos e subdiretórios em um diretório:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create a ListObjectsV2Request request to list objects. ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName); // Set Prefix to fun/ to list all objects and subdirectories in the fun/ directory. listObjectsV2Request.setPrefix("fun/"); // Set the delimiter to a forward slash (/). listObjectsV2Request.setDelimiter("/"); // Initiate the request. ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request); // Traverse all objects. System.out.println("Objects:"); // In the response, objectSummaries lists the objects in the fun/ directory. for (OSSObjectSummary objectSummary : result.getObjectSummaries()) { System.out.println(objectSummary.getKey()); } // Traverse all CommonPrefix elements. System.out.println("\nCommonPrefixes:"); // CommonPrefixs lists all subdirectories in the fun/ directory. The fun/movie/001.avi and fun/movie/007.avi objects are not listed because they are in the movie/ subdirectory of the fun/ directory. for (String commonPrefix : result.getCommonPrefixes()) { System.out.println(commonPrefix); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } -
Ao chamar as duas operações anteriores para listar objetos e subdiretórios no diretório especificado, a seguinte resposta é retornada:
Objects: fun/test.jpg CommonPrefixes: fun/movie/
Listar os tamanhos dos objetos em um diretório específico
-
O exemplo a seguir mostra como chamar a operação GetBucket (ListObjects) para listar os tamanhos dos objetos em um diretório específico:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.CredentialsProviderFactory; import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.OSSObjectSummary; import com.aliyun.oss.model.ObjectListing; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Specify the prefix in the names of the objects that you want to list. Example: exampledir/. If you want to traverse the sizes of objects and directories in the root directory, leave this parameter empty. String prefix = "exampledir/"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { long totalSize = 0; int totalCount = 0; String nextMarker = null; final int maxKeys = 1000; do { ObjectListing objectListing = ossClient.listObjects(bucketName, prefix); for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) { totalSize += objectSummary.getSize(); totalCount++; // Output the name and size of each object. System.out.println("File: " + objectSummary.getKey() + " | Size: " + objectSummary.getSize() + " bytes (" + formatSize(objectSummary.getSize()) + ")"); } nextMarker = objectListing.getNextMarker(); } while (nextMarker != null && !nextMarker.isEmpty()); System.out.println("Folder: " + prefix); System.out.println("Total objects: " + totalCount); System.out.println("Total size (bytes): " + totalSize); System.out.println("Total size (human readable): " + formatSize(totalSize)); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } // Convert bytes into a readable format. public static String formatSize(long size) { String[] units = {"B", "KB", "MB", "GB", "TB", "PB"}; int unitIndex = 0; double sizeD = size; while (sizeD >= 1024 && unitIndex < units.length - 1) { sizeD /= 1024; unitIndex++; } return String.format("%.2f %s", sizeD, units[unitIndex]); } } -
O exemplo a seguir mostra como chamar a operação GetBucketV2 (ListObjectsV2) para listar os tamanhos dos objetos em um diretório:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.CredentialsProviderFactory; import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.ListObjectsV2Request; import com.aliyun.oss.model.ListObjectsV2Result; import com.aliyun.oss.model.OSSObjectSummary; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Specify the prefix in the names of the objects that you want to list. Example: exampledir/. If you want to traverse the sizes of objects and directories in the root directory, leave this parameter empty. String prefix = "exampledir/"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { long totalSize = 0; int totalCount = 0; String continuationToken = null; final int maxKeys = 1000; do { ListObjectsV2Request request = new ListObjectsV2Request(bucketName) .withPrefix(prefix) .withMaxKeys(maxKeys) .withContinuationToken(continuationToken); ListObjectsV2Result result = ossClient.listObjectsV2(request); for (OSSObjectSummary objectSummary : result.getObjectSummaries()) { totalSize += objectSummary.getSize(); totalCount++; System.out.println("File: " + objectSummary.getKey() + " | Size: " + objectSummary.getSize() + " bytes (" + formatSize(objectSummary.getSize()) + ")"); } continuationToken = result.getNextContinuationToken(); } while (continuationToken != null); System.out.println("\nFolder: " + prefix); System.out.println("Total objects: " + totalCount); System.out.println("Total size (bytes): " + totalSize); System.out.println("Total size (human readable): " + formatSize(totalSize)); }catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } // Convert bytes into a readable format. public static String formatSize(long size) { String[] units = {"B", "KB", "MB", "GB", "TB", "PB"}; int unitIndex = 0; double sizeD = size; while (sizeD >= 1024 && unitIndex < units.length - 1) { sizeD /= 1024; unitIndex++; } return String.format("%.2f %s", sizeD, units[unitIndex]); } }
Referências
Para obter o código de exemplo completo usado para listar objetos, visite o GitHub.
Para mais informações sobre as operações de API usadas para listar objetos, consulte GetBucket (ListObjects) e ListObjectsV2 (GetBucketV2).
Para mais informações sobre como listar e gerencie LiveChannels, consulte Gerenciar LiveChannels (Java SDK V1).