Listing Objects (SDK for Java)
Function
This API lists some or all of the objects in a bucket. You can use parameters such as the prefix, number of returned objects, and start position to list objects that meet specified criteria. Returned objects are listed in alphabetical order by object name.
If you have any questions during development, post them on the Issues page of GitHub.
Restrictions
- To list objects in a bucket, you must be the bucket owner or have the required permission (obs:bucket:ListBucket in IAM or ListBucket in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Creating a Custom Bucket Policy.
- The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.
- A maximum of 1,000 object versions can be returned in a single request. If a bucket contains more than 1,000 object versions, you can use pagination to list all versions. If ListVersionsResult.isTruncated is true, only part of object versions are returned. In this case, you can use ListVersionsResult.getNextKeyMarker and ListVersionsResult.getNextVersionIdMarker to obtain the start position for the next listing.
Method
obsClient.listObjects(ListObjectsRequest request)
Request Parameters
Parameter |
Type |
Mandatory (Yes/No) |
Description |
---|---|---|---|
request |
Yes |
Explanation: Request parameters for listing the objects in a bucket. For details, see Table 2. |
Parameter |
Type |
Mandatory (Yes/No) |
Description |
---|---|---|---|
bucketName |
String |
Yes |
Explanation: Bucket name. Restrictions:
Default value: None |
prefix |
String |
No |
Explanation: Name prefix that the objects to be listed must contain. Assume that you have the following objects: logs/day1, logs/day2, logs/day3, and ExampleObject.jpg. If you specify logs/ as the prefix, logs/day1, logs/day2, and logs/day3 will be returned. If this parameter is null and there are no other filter criteria, all objects in the bucket will be returned. Value range: The value must contain 1 to 1,024 characters. Default value: None |
marker |
String |
No |
Explanation: Name of the object to start with when listing objects in a bucket. All objects following this object are listed in alphabetical order by object name. Assume that you have the following objects: test/a, test/b, test/c, and test/d. If you specify test/b as the marker, test/c and test/d are returned. Restrictions: This parameter is only available for listing objects with a single version. Value range: The value must contain 1 to 1,024 characters. Default value: None |
maxKeys |
int |
No |
Explanation: The maximum number of objects returned in the response in alphabetical order. Value range: The value ranges from 1 to 1000. If the specified value is beyond this range, only 1,000 objects are returned. Default value: 1000 |
delimiter |
String |
No |
Explanation: Object names are grouped by this parameter, which is often used with Prefix. If a prefix is specified, objects with the same string from the prefix to the first delimiter are grouped into one CommonPrefixes. If no prefix is specified, objects with the same string from the first character to the first delimiter are grouped into one CommonPrefixes. Assume that a bucket has objects abcd, abcde, and bbcde in it. If delimiter is set to d and prefix is set to a, files abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix. If only delimiter is set to d, files abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix, and bbcde is grouped separately into another CommonPrefixes with bbcd as the prefix. For a PFS, if this parameter is not specified, all the contents in the current directory are recursively listed by default, and subdirectories are also listed. In big data scenarios, PFSs usually have multiple directory levels and each directory level has a large number of files. In such case, you are advised to configure [delimiter=/] to list the contents in the current directory but exclude the contents in subdirectories, thereby accelerating the listing. Value range: The value must contain 1 to 1,024 characters. Default value: None |
encodingType |
String |
No |
Explanation: Encoding type for some elements in the response. If delimiter, marker, prefix, nextMarker, and objectKey contain control characters that are not supported by the XML 1.0 standard, you can set encodingType to encode delimiter, marker, prefix (including the prefix in commonPrefixes), nextMarker, and objectKey in the response. Value range: url Default value: None. If you leave this parameter blank, encoding is not applied. |
Responses
Parameter |
Type |
Description |
---|---|---|
bucketName |
String |
Explanation: Bucket name. Restrictions:
Default value: None |
prefix |
String |
Explanation: Object name prefix. Assume that you have the following objects: logs/day1, logs/day2, logs/day3, and ExampleObject.jpg. If you specify logs/ as the prefix, logs/day1, logs/day2, and logs/day3 will be returned. If this parameter is null and there are no other filter criteria, all objects in the bucket will be returned. Value range: The value must contain 1 to 1,024 characters. Default value: None |
objectSummaries |
List<ObsObject> |
Explanation: List of objects in the bucket. For details, see Table 4. |
commonPrefixes |
List<String> |
Explanation: List of object name prefixes grouped according to the delimiter parameter (if specified) Value range: The value must contain 1 to 1,024 characters. Default value: None |
truncated |
boolean |
Explanation: Whether all objects are returned in the response. A maximum of 1,000 objects can be listed at a time. If the number of objects is greater than 1,000, the objects beyond 1,000 cannot be returned. Value range: true: Not all objects are returned. false: All objects are returned. Default value: None |
marker |
String |
Explanation: Where in the bucket the listing starts from. All objects following the object specified by this parameter are listed in alphabetical order by object name. Assume you have the following objects: test/a, test/b, test/c, and test/d. If you specify test/b as the marker, test/c and test/d are returned. Restrictions: This parameter is only available for listing objects with a single version. Value range: The value must contain 1 to 1,024 characters. Default value: None |
maxKeys |
int |
Explanation: The maximum number of objects returned in the response in alphabetical order. Value range: The value ranges from 1 to 1000. If the specified value is beyond this range, only 1,000 objects are returned. Default value: 1000 |
delimiter |
String |
Explanation: Object names are grouped by this parameter, which is often used with Prefix. If a prefix is specified, objects with the same string from the prefix to the first delimiter are grouped into one CommonPrefixes. If no prefix is specified, objects with the same string from the first character to the first delimiter are grouped into one CommonPrefixes. Assume that a bucket has objects abcd, abcde, and bbcde in it. If delimiter is set to d and prefix is set to a, files abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix. If only delimiter is set to d, files abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix, and bbcde is grouped separately into another CommonPrefixes with bbcd as the prefix. For a PFS, if this parameter is not specified, all the contents in the current directory are recursively listed by default, and subdirectories are also listed. In big data scenarios, PFSs usually have multiple directory levels and each directory level has a large number of files. In such case, you are advised to configure [delimiter=/] to list the contents in the current directory but exclude the contents in subdirectories, thereby accelerating the listing. Value range: The value must contain 1 to 1,024 characters. Default value: None |
nextMarker |
String |
Explanation: Where in the bucket the next listing begins. If not all objects are returned, the response contains this parameter to mark the last object returned for the current request. You can use the value of this parameter as the value of Marker in the subsequent request to list the remaining objects. Value range: The value must contain 1 to 1,024 characters. Default value: None |
location |
String |
Explanation: Region where a bucket is located. Restrictions: If the endpoint used is obs.myhuaweicloud.com, this parameter is not required. If any other endpoints are used, this parameter is required. Value range: To learn about valid regions and endpoints, see Regions and Endpoints. An endpoint is the request address for calling an API. Endpoints vary depending on services and regions. To obtain the regions and endpoints, contact the enterprise administrator. Default value: If obs.myhuaweicloud.com is used as the endpoint and no region is specified, cn-north-1 (the CN North-Beijing1 region) is used by default. |
statusCode |
int |
Explanation: HTTP status code. Value range: A status code is a group of digits that can be 2xx (indicating successes) or 4xx or 5xx (indicating errors). It indicates the status of a response. For more information, see Status Code. Default value: None |
responseHeaders |
Map<String, Object> |
Explanation: Response header list, composed of tuples. In a tuple, the String key indicates the name of the header, and the Object value indicates the value of the header. Default value: None |
Parameter |
Type |
Description |
---|---|---|
objectKey |
String |
Explanation: Object name. An object is uniquely identified by an object name in a bucket. An object name is a complete path that does not contain the bucket name. For example, if the address for accessing the object is examplebucket.obs.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt. Value range: The value must contain 1 to 1,024 characters. Default value: None |
bucketName |
String |
Explanation: Bucket name. Restrictions:
Default value: None |
objectContent |
InputStream |
Explanation: The data stream of the object. Default value: None |
owner |
Explanation: Object owner. This parameter contains the domain ID and name of the object owner. For details, see Table 5. Default value: None |
|
metadata |
Explanation: Object metadata. Value range: Object metadata. For details, see Table 7. Default value: None |
Parameter |
Type |
Mandatory (Yes/No) |
Description |
---|---|---|---|
id |
String |
Yes |
Explanation: Account (domain) ID of the bucket owner. Value range: To obtain the account ID, see How Do I Get My Account ID and User ID? Default value: None |
displayName |
String |
No |
Explanation: Account name of the owner. Value range: To obtain the account name, see How Do I Get My Account ID and User ID? Default value: None |
Constant |
Default Value |
Description |
---|---|---|
STANDARD |
STANDARD |
Standard storage class |
WARM |
WARM |
Infrequent Access storage class. |
COLD |
COLD |
Archive storage class. |
Parameter |
Type |
Mandatory (Yes/No) |
Description |
---|---|---|---|
contentLength |
Long |
No |
Explanation: Object size. Restrictions:
Default value: If this parameter is not specified, the SDK automatically calculates the size of the object. |
contentType |
String |
No |
Explanation: MIME type of the object file. MIME type is a standard way of describing a data type and is used by the browser to decide how to display data. Value range: See What Is Content-Type (MIME)? (Java SDK) Default value: If this parameter is not specified, the SDK determines the file type based on the suffix of the object name and assigns a value to the parameter. For example, if the suffix of the object name is .xml, the object is an application/xml file. If the suffix is .html, the object is a text/html file. |
contentEncoding |
String |
No |
Explanation: Content-Encoding header in the response. It specifies which encoding is applied to the object. Default value: None |
contentDisposition |
String |
No |
Explanation: Provides a default file name for the requested object. When the object with the default file name is being downloaded or accessed, the content is displayed as part of a web page in the browser or as an attachment in a download dialog box. Default value: None |
cacheControl |
String |
No |
Explanation: Cache-Control header in the response. It specifies the cache behavior of the web page when an object is downloaded. Default value: None |
contentLanguage |
String |
No |
Explanation: Language or language combination for visitors to customize and use. For details, see the definition of ContentLanguage in the HTTP protocol. Default value: None |
expires |
String |
No |
Explanation: The time a cached web page object expires. Restrictions: The time must be in the GMT format. Default value: None |
contentMd5 |
String |
No |
Explanation: Base64-encoded MD5 value of the object data. It is provided for the OBS server to verify data integrity. The OBS server will compare this MD5 value with the MD5 value calculated based on the object data. If the two values are not the same, HTTP status code 400 is returned. Restrictions:
Value range: Base64-encoded 128-bit MD5 value of the request body calculated according to RFC 1864. Example: n58IG6hfM7vqI4K0vnWpog== Default value: None |
storageClass |
No |
Explanation: Storage class of an object that can be specified at object creation. If you do not specify this header, the object inherits the storage class of the bucket. Value range: See Table 6. Default value: None |
|
webSiteRedirectLocation |
String |
No |
Explanation: If the bucket is configured with website hosting, the request for obtaining the object can be redirected to another object in the bucket or an external URL. This parameter specifies the address the request for the object is redirected to. The request is redirected to an object anotherPage.html in the same bucket: WebsiteRedirectLocation:/anotherPage.html The request is redirected to an external URL http://www.example.com/: WebsiteRedirectLocation:http://www.example.com/ Restrictions:
Default value: None |
nextPosition |
long |
No |
Explanation: Start position for the next append upload. Value range: 0 to the object length, in bytes. Default value: None |
appendable |
boolean |
No |
Explanation: Whether the object is appendable. Value range: true: The object is appendable. false: The object is not appendable. Default value: None |
userMetadata |
Map<String, Object> |
No |
Explanation: User-defined metadata of the object. To define it, you can add a header starting with x-obs-meta- in the request. In Map, the String key indicates the name of the user-defined metadata that starts with x-obs-meta-, and the Object value indicates the value of the user-defined metadata. To obtain the user-defined metadata of an object, use ObsClient.getObjectMetadata. For details, see Obtaining Object Metadata (SDK for Java). Restrictions:
Default value: None |
Code Example: Listing Objects in a Bucket
This example list objects in bucket examplebucket. A maximum of 1,000 objects can be returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObsObject; public class ListObjects001 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use the permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk,endPoint); // Use the temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { // Listing objects. ObjectListing result = obsClient.listObjects("examplebucket"); for (ObsObject obsObject : result.getObjects()) { System.out.println("listObjects successfully"); System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } } catch (ObsException e) { System.out.println("listObjects failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error details. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("listObjects failed"); // Print other error information. e.printStackTrace(); } } } |
Code Example: Specifying the Object Count for Listing
This example lists a specified number of objects in bucket examplebucket. A maximum of 100 objects can be listed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.ListObjectsRequest; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObsObject; public class ListObjects002 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use the permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk,endPoint); // Use the temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { // List a specified number of objects. ListObjectsRequest request = new ListObjectsRequest("examplebucket"); // Set the number of objects to be listed to 100. request.setMaxKeys(100); ObjectListing result = obsClient.listObjects(request); for (ObsObject obsObject : result.getObjects()) { System.out.println("listObjects successfully"); System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } } catch (ObsException e) { System.out.println("listObjects failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error details. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("listObjects failed"); // Print other error information. e.printStackTrace(); } } } |
Code Example: Specifying the Prefix for Listing
This example specifies a prefix to list objects in bucket examplebucket. A maximum of 100 objects can be listed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.ListObjectsRequest; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObsObject; public class ListObjects003 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use the permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk,endPoint); // Use the temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { // List objects by specifying a prefix. ListObjectsRequest request = new ListObjectsRequest("examplebucket"); // List 100 objects with the specified prefix. request.setMaxKeys(100); request.setPrefix("prefix"); ObjectListing result = obsClient.listObjects(request); for (ObsObject obsObject : result.getObjects()) { System.out.println("listObjects successfully"); System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } } catch (ObsException e) { System.out.println("listObjects failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error details. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("listObjects failed"); // Print other error information. e.printStackTrace(); } } } |
Code Example: Specifying the Start Position for Listing
This example specifies a start position to list objects in bucket examplebucket. A maximum of 100 objects can be listed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.ListObjectsRequest; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObsObject; public class ListObjects004 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use the permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk,endPoint); // Use the temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { // List objects by specifying the start position. ListObjectsRequest request = new ListObjectsRequest("examplebucket"); // Specify that 100 objects whose names follow test in lexicographical order will be listed. request.setMaxKeys(100); request.setMarker("test"); ObjectListing result = obsClient.listObjects(request); for (ObsObject obsObject : result.getObjects()) { System.out.println("listObjects successfully"); System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } } catch (ObsException e) { System.out.println("listObjects failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error details. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("listObjects failed"); // Print other error information. e.printStackTrace(); } } } |
Code Example: Using Pagination to List All Objects
This example lists all objects in bucket examplebucket using pagination. A maximum of 100 objects can be listed on each page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.ListObjectsRequest; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObsObject; public class ListObjects005 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use the permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk,endPoint); // Use the temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { // List all objects using pagination. ListObjectsRequest request = new ListObjectsRequest("examplebucket"); // Set the number of objects displayed per page to 100. request.setMaxKeys(100); ObjectListing result; do { result = obsClient.listObjects(request); for (ObsObject obsObject : result.getObjects()) { System.out.println("listObjects successfully"); System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } request.setMarker(result.getNextMarker()); } while (result.isTruncated()); } catch (ObsException e) { System.out.println("listObjects failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error details. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("listObjects failed"); // Print other error information. e.printStackTrace(); } } } |
Code Example: Listing Objects in a Folder
There is no concept of folders in OBS. All elements stored in OBS buckets are objects. Folders are actually objects whose sizes are 0 and whose names end with a slash (/). You can set a folder name as a prefix to list objects in this folder. This example lists objects in a folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.ListObjectsRequest; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObsObject; public class ListObjects006 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use the permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk,endPoint); // Use the temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { //List all objects in a folder. ListObjectsRequest request = new ListObjectsRequest("examplebucket"); // Set folder name dir/ as the prefix. request.setPrefix("dir/"); request.setMaxKeys(100); ObjectListing result; do { result = obsClient.listObjects(request); for (ObsObject obsObject : result.getObjects()) { System.out.println("listObjects successfully"); System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } request.setMarker(result.getNextMarker()); } while (result.isTruncated()); } catch (ObsException e) { System.out.println("listObjects failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error details. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("listObjects failed"); // Print other error information. e.printStackTrace(); } } } |
Code Example: Listing All Objects in a Bucket by Folder Name
This example lists all objects in bucket examplebucket.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.ListObjectsRequest; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObsObject; public class ListObjects007 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use the permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk,endPoint); // Use the temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { // List all objects in the root directory. ListObjectsRequest request = new ListObjectsRequest("examplebucket"); request.setMaxKeys(1000); // Set folder isolators to slashes (/). request.setDelimiter("/"); ObjectListing result = obsClient.listObjects(request); System.out.println("Objects in the root directory:"); for (ObsObject obsObject : result.getObjects()) { System.out.println("listObjects successfully"); System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } listObjectsByPrefix(obsClient, request, result); } catch (ObsException e) { System.out.println("listObjects failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error details. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("listObjects failed"); // Print other error information. e.printStackTrace(); } } |
Code Example: Recursively Listing Objects in a Sub-folder
This example recursively lists objects in a sub-folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Recursively list objects in a sub-folder. static void listObjectsByPrefix(ObsClient obsClient, ListObjectsRequest request, ObjectListing result) throws ObsException { for (String prefix : result.getCommonPrefixes()) { System.out.println("Objects in folder [" + prefix + "]:"); request.setPrefix(prefix); result = obsClient.listObjects(request); for (ObsObject obsObject : result.getObjects()) { System.out.println("ObjectKey:" + obsObject.getObjectKey()); System.out.println("Owner:" + obsObject.getOwner()); } listObjectsByPrefix(obsClient, request, result); } } } |
- The sample code does not apply to scenarios where the number of objects in a folder exceeds 1,000.
- Since all folder names end with a slash (/) and the objects and sub-folders to list are under the folder, delimiter is always a slash (/).
- In the returned result of each recursion, ObjectListing.getObjects includes the objects under the folder, and ObjectListing.getCommonPrefixes includes the sub-folders under the folder.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot