En este tema se describe cómo listar todos los objetos, un número específico de objetos y aquellos cuyos nombres contienen un prefijo determinado dentro de un bucket de Object Storage Service (OSS).
Notas de uso
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.
Las credenciales de acceso se obtienen a partir de variables de entorno. Para más información, consulte 配置访问凭证.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Client configuration.
Para listar objetos, debe contar con el permiso
oss:ListObjects. Para más información, consulte Grant a custom policy.
Contexto
-
GetBucket (ListObjects)
Puede invocar la operación GetBucket (ListObjects) con cualquiera de los siguientes formatos:
ObjectListing listObjects(String bucketName): lista todos los objetos de un bucket. De forma predeterminada, una sola solicitud puede listar hasta 100 objetos.
ObjectListing listObjects(String bucketName, String prefix): lista los objetos de un bucket cuyos nombres contienen un prefijo específico. De forma predeterminada, una sola solicitud puede listar hasta 100 objetos.
ObjectListing listObjects(ListObjectsRequest listObjectsRequest): lista los objetos que cumplen las condiciones especificadas. Este formato permite listar objetos de manera flexible.
A continuación se describen los parámetros que puede especificar al invocar la operación GetBucket (ListObjects).
Parámetro
Descripción
Método
objectSummaries
Los metadatos de los objetos que desea listar.
List<OSSObjectSummary> getObjectSummaries()
prefix
El prefijo en los nombres de los objetos que desea listar.
String getPrefix()
delimiter
El carácter que se usa para agrupar por nombre los objetos que desea listar.
String getDelimiter()
marker
La posición desde donde inicia la operación de listado.
String getMarker()
maxKeys
El número máximo de objetos que se pueden listar a la vez.
int getMaxKeys()
nextMarker
La posición desde donde inicia la siguiente operación de listado.
String getNextMarker()
isTruncated
Indica si el listado de objetos está truncado. Valores válidos:
false: todos los objetos se listan sin truncamiento.
true: solo se lista una parte de los objetos.
boolean isTruncated()
commonPrefixes
Un conjunto de subcadenas de los nombres de los objetos. Los objetos cuyos nombres terminan con el delimitador y comparten el mismo prefijo se agrupan como un único elemento de resultado en CommonPrefixes.
List<String> getCommonPrefixes()
encodingType
El tipo de codificación de los nombres de los objetos en la respuesta.
String getEncodingType()
-
GetBucketV2 (ListObjectsV2)
Puede invocar la operación GetBucketV2 (ListObjectsV2) con cualquiera de los siguientes formatos:
ListObjectsV2Result listObjectsV2(String bucketName): lista todos los objetos de un bucket. De forma predeterminada, una sola solicitud puede listar hasta 100 objetos.
ListObjectsV2Result listObjectsV2(String bucketName, String prefix): lista los objetos de un bucket cuyos nombres contienen un prefijo específico. De forma predeterminada, una sola solicitud puede listar hasta 100 objetos.
ListObjectsV2Result listObjectsV2(ListObjectsRequest listObjectsRequest): lista los objetos que cumplen las condiciones especificadas. Este formato permite listar objetos de manera flexible.
A continuación se describen los parámetros que puede especificar al invocar la operación GetBucketV2 (ListObjectsV2).
Parámetro
Descripción
Método
objectSummaries
Los metadatos de los objetos que desea listar.
List<OSSObjectSummary> getObjectSummaries()
prefix
El prefijo en los nombres de los objetos que desea listar.
String getPrefix()
delimiter
El carácter que se usa para agrupar por nombre los objetos que desea listar.
String getDelimiter()
startAfter
La posición desde donde inicia la operación de listado.
String getStartAfter()
maxKeys
El número máximo de objetos que se pueden listar a la vez.
int getMaxKeys()
continuationToken
La posición desde donde inicia la operación de listado.
String getContinuationToken()
nextContinuationToken
La posición desde donde inicia la siguiente operación de listado.
String getNextContinuationToken()
isTruncated
Indica si el listado de objetos está truncado. Valores válidos:
false: todos los objetos se listan sin truncamiento.
true: solo se lista una parte de los objetos.
boolean isTruncated()
commonPrefixes
Un conjunto de subcadenas de los nombres de los objetos. Los objetos cuyos nombres terminan con el delimitador y comparten el mismo prefijo se agrupan como un único elemento de resultado en CommonPrefixes.
List<String> getCommonPrefixes()
encodingType
El tipo de codificación de los nombres de los objetos en la respuesta.
String getEncodingType()
fetchOwner
Indica si se incluye la información del propietario del objeto en la respuesta. Valores válidos:
true: la respuesta incluye la información del propietario del objeto.
false: la respuesta no incluye la información del propietario del objeto.
String getFetchOwner()
Listar objetos mediante un listado simple
Para listar los objetos de un bucket específico, invoque la operación GetBucket (ListObjects) o GetBucketV2 (ListObjectsV2).
Invocar la operación GetBucket (ListObjects) para listar objetos
El siguiente código de ejemplo muestra cómo invocar la operación GetBucket (ListObjects) para listar los objetos de un bucket específico. De forma predeterminada, cada solicitud 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();
}
}
}
}
Invocar la operación GetBucketV2 (ListObjectsV2) para listar objetos
El siguiente código de ejemplo muestra cómo invocar la operación GetBucketV2 (ListObjectsV2) para listar los objetos de un bucket específico. De forma predeterminada, cada solicitud 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();
}
}
}
}
Invocar la operación ListObjectsRequest para listar objetos
Al invocar la operación ListObjectsRequest, especifique parámetros para listar objetos de manera flexible. A continuación se describen los parámetros que puede configurar en esta operación.
|
Parámetro |
Descripción |
Método |
|
prefix |
El prefijo que deben incluir los nombres de los objetos que desea listar. |
setPrefix(String prefix) |
|
delimiter |
El carácter que se usa para agrupar por nombre los objetos que desea listar. Por ejemplo, puede establecer la barra diagonal (/) como delimitador. Los objetos cuyos nombres comparten la misma cadena, desde el prefijo especificado hasta la primera aparición de la barra diagonal (/), se agrupan como un elemento CommonPrefixes. Se listan todos los objetos cuyos nombres contienen los elementos CommonPrefixes. Utilice el parámetro delimiter para gestionar y consultar objetos de forma jerárquica, lo que garantiza resultados más organizados e intuitivos. |
setDelimiter(String delimiter) |
|
marker |
La posición desde donde inicia la operación de listado. Se listan los objetos cuyos nombres son alfabéticamente posteriores al valor de marker. |
setMarker(String marker) |
|
maxKeys |
El número máximo de objetos que se pueden listar a la vez. Una vez establecido este parámetro, los objetos se listan en orden alfabético. Valor máximo: 1000. Valor predeterminado: 100. |
setMaxKeys(Integer maxKeys) |
|
encodingType |
El tipo de codificación de los nombres de los objetos en la respuesta. Valor válido: URL. |
setEncodingType(String encodingType) |
Listar un número específico de objetos
El siguiente código de ejemplo muestra cómo listar un número específico de objetos en un 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 cuyos nombres contienen un prefijo específico
El siguiente código de ejemplo muestra cómo listar los objetos de un bucket cuyos nombres contienen un prefijo 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.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 cuyos nombres son alfabéticamente posteriores al valor de marker
El siguiente código de ejemplo muestra cómo listar los objetos cuyos nombres son alfabéticamente posteriores al 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 los objetos de un bucket por página
El siguiente código de ejemplo muestra cómo listar por páginas todos los objetos de un bucket. Utilice maxKeys para especificar el número máximo de objetos que se muestran en 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 por páginas los objetos cuyos nombres contienen un prefijo específico
El siguiente código de ejemplo muestra cómo listar por páginas los objetos cuyos nombres contienen un prefijo 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.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 cuyos nombres están codificados con un tipo de codificación específico
Si el nombre de un objeto contiene alguno de los siguientes caracteres, debe codificarse con URL antes de transmitirlo. OSS solo admite la codificación URL.
Comillas simples (')
Comillas dobles (")
Signos et (&)
Corchetes angulares (<>)
Marcas de pausa (、)
Caracteres chinos
El siguiente código de ejemplo muestra cómo listar objetos cuyos nombres están codificados con un tipo de codificación 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();
}
}
}
}
Llamar a la operación ListObjectsV2Request para listar objetos
Al llamar a la operación ListObjectsV2Request, usted puede especificar parámetros para listar objetos de manera flexible. Por ejemplo, es posible listar una cantidad específica de objetos, aquellos cuyos nombres contienen un prefijo determinado o todos los objetos de un bucket por página.
A continuación se describen los parámetros que se pueden especificar al llamar a la operación ListObjectsV2Request.
|
Parámetro |
Descripción |
Método |
|
prefix |
Prefijo que deben incluir los nombres de los objetos que desea listar. |
setPrefix(String prefix) |
|
delimiter |
Carácter que se utiliza para agrupar por nombre los objetos que desea listar. Por ejemplo, puede establecer el delimitador como una barra diagonal (/). Los objetos cuyos nombres comparten la misma cadena, desde el prefijo especificado hasta la primera aparición de la barra diagonal (/), se agrupan como un elemento CommonPrefixes. Se listan todos los objetos cuyos nombres contienen elementos CommonPrefixes. Este parámetro permite gestionar y consultar objetos de forma jerárquica, lo que genera resultados más organizados e intuitivos. |
setDelimiter(String delimiter) |
|
maxKeys |
Número máximo de objetos que se pueden listar a la vez. Una vez que se especifica este parámetro, los objetos se listan en orden alfabético. Valor máximo: 1000. Valor predeterminado: 100. |
setMaxKeys(Integer maxKeys) |
|
startAfter |
Posición desde donde inicia la operación de listado. Se listan los objetos cuyos nombres van después del valor de startAfter en orden alfabético. |
setStartAfter(String startAfter) |
|
continuationToken |
El continuationToken que se utiliza en esta operación de listado. |
setContinuationToken(String continuationToken) |
|
encodingType |
Tipo de codificación de los nombres de objeto en la respuesta. Valor válido: URL. |
setEncodingType(String encodingType) |
|
fetchOwner |
Indica si se incluye la información del propietario en la respuesta. |
setFetchOwner(boolean fetchOwner ) |
Listar una cantidad específica de objetos
El siguiente código de ejemplo muestra cómo listar una cantidad específica de objetos en un 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 cuyos nombres contienen un prefijo específico
El siguiente código de ejemplo muestra cómo listar los objetos de un bucket cuyos nombres contienen un prefijo 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.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 cuyos nombres siguen alfabéticamente al valor de startAfter
El siguiente código de ejemplo muestra cómo listar los objetos cuyos nombres siguen alfabéticamente al 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 y su información de propietario
El siguiente código de ejemplo muestra cómo listar objetos junto con la información de sus propietarios:
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 los objetos de un bucket por página
El siguiente código de ejemplo muestra cómo listar por página todos los objetos de un bucket. Utilice maxKeys para especificar el número máximo de objetos que se pueden listar en 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 por página objetos cuyos nombres contienen un prefijo específico
El siguiente código de ejemplo muestra cómo listar por página los objetos cuyos nombres contienen un prefijo 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.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 cuyos nombres están codificados con un tipo de codificación específico
El siguiente código de ejemplo muestra cómo listar objetos cuyos nombres están codificados con un tipo de codificación 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 directorio
OSS utiliza una estructura plana para almacenar los objetos. Un directorio es un objeto de cero bytes cuyo nombre termina con una barra diagonal (/). Este objeto se puede cargar y descargar. De forma predeterminada, la consola de OSS muestra como directorio cualquier objeto cuyo nombre termine con una barra diagonal (/). Para consultar el código de ejemplo completo que se usa para crear directorios, visite GitHub.
Para listar objetos por directorio, especifique los parámetros delimiter y prefix.
Si establece
prefixcon el nombre de un directorio en la solicitud, se listan los objetos y subdirectorios cuyos nombres contienen ese prefijo.Si especifica un prefijo y establece
delimitercon una barra diagonal (/) en la solicitud, se listan los objetos y subdirectorios del directorio cuyos nombres comienzan con dicho prefijo. Cada subdirectorio aparece como un único elemento de resultado enCommonPrefixes. Los objetos y directorios dentro de estos subdirectorios no se listan.
Por ejemplo, suponga que un bucket contiene los siguientes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi y fun/movie/007.avi. Se configura la barra diagonal (/) como delimitador de directorio. A continuación se describe cómo listar objetos en directorios simulados.
Listar todos los objetos del bucket
-
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucket (ListObjects) para listar todos los objetos del 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(); } } } } -
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucketV2 (ListObjectsV2) para listar todos los objetos de un 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 respuesta
Los dos métodos anteriores devuelven la siguiente respuesta al listar todos los objetos de un bucket:
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg oss.jpg CommonPrefixes:
Listar todos los objetos de un directorio
-
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucket (ListObjects) para listar todos los objetos de un directorio:
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(); } } } } -
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucketV2 (ListObjectsV2) para listar todos los objetos de un directorio 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(); } } } } -
Las dos operaciones anteriores devuelven la siguiente respuesta al listar todos los objetos del directorio especificado:
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg CommonPrefixes:
Listar objetos y subdirectorios de un directorio específico
-
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucket (ListObjects) para listar los objetos y subdirectorios de un directorio 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(); } } } } -
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucketV2 (ListObjectsV2) para listar los objetos y subdirectorios de un directorio:
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(); } } } } -
Al llamar a las dos operaciones anteriores para listar los objetos y subdirectorios del directorio especificado, se devuelve la siguiente respuesta:
Objects: fun/test.jpg CommonPrefixes: fun/movie/
Listar los tamaños de los objetos de un directorio específico
-
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucket (ListObjects) para listar los tamaños de los objetos de un directorio 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]); } } -
El siguiente código de ejemplo muestra cómo llamar a la operación GetBucketV2 (ListObjectsV2) para listar los tamaños de los objetos de un directorio:
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]); } }
Referencias
Para consultar el código de ejemplo completo que se usa para listar objetos, visite GitHub.
Para obtener más información sobre las operaciones de API que permiten listar objetos, consulte GetBucket (ListObjects) y ListObjectsV2 (GetBucketV2).
Para conocer cómo listar y gestionar LiveChannels, consulte Manage LiveChannels (Java SDK V1).