You can delete a single object, multiple specified objects, objects with a specific name prefix, or a specific directory and all objects within it.
Deleted objects cannot be recovered. Exercise caution when you delete objects.
Usage notes
In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see Regions and endpoints.
In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.
In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Configuration examples for common scenarios.
To delete an object, you must have the
oss:DeleteObject
permission. For more information, see Attach a custom policy to a RAM user.
Delete a single object
The following sample code shows how to delete an object named exampleobject.txt from a bucket named examplebucket:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 full path of the object. Do not include the bucket name in the full path of the object. String objectName = "exampleobject.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 associated 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 { // Delete the object or the directory. Before you delete a directory, make sure that the directory does not contain objects. ossClient.deleteObject(bucketName, objectName); } 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(); } } } }
Delete multiple objects at a time
You can manually delete up to 1,000 objects at a time. You can delete multiple specified objects, objects with a specified prefix, or a directory and all objects within it.
You can also configure lifecycle rules to automatically delete objects. For more information, see Lifecycle rules based on the last modified time.
Parameters
Request parameters
Parameter
Description
Method
Keys
The objects that you want to delete.
setKeys(List<String>)
quiet
Results are returned in one of two modes, with verbose mode as the default. You can select the mode that you require.
Verbose mode: All deleted objects are returned. This is the default return mode. If you set the quiet parameter to false or do not configure the quiet parameter, the result is returned in this mode.
Basic mode: If quiet is set to true, the return mode is quiet, in which the response does not include the deleted objects.
setQuiet(boolean)
encodingType
The method that you want to use to encode the object names in the result. Only URL encoding is supported.
setEncodingType(String)
Response parameters
Parameter
Description
Method
deletedObjects
The result of the delete operation.
In the verbose mode, a list of deleted objects is returned. The objects that were specified in the delete operation but do not exist are also included in the result.
In basic mode, the response does not include the deleted objects.
List<String> getDeletedObjects()
encodingType
The method used to encode the object names in the result. If this parameter is empty, the object names are not encoded.
getEncodingType()
Delete multiple objects with specified names
The following sample code shows how to delete multiple objects with specified names:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.DeleteObjectsRequest; import com.aliyun.oss.model.DeleteObjectsResult; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; 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 associated 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 { // Delete the objects. // Specify the full paths of the multiple objects that you want to delete. Do not include the bucket name in the full paths of the objects. List<String> keys = new ArrayList<String>(); keys.add("exampleobjecta.txt"); keys.add("testfolder/sampleobject.txt"); keys.add("exampleobjectb.txt"); DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url")); List<String> deletedObjects = deleteObjectsResult.getDeletedObjects(); try { for(String obj : deletedObjects) { String deleteObj = URLDecoder.decode(obj, "UTF-8"); System.out.println(deleteObj); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } 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(); } } } }
Delete multiple objects with a specified prefix or from a specified directory
The following sample code shows how to delete multiple objects with a specified prefix and how to delete a specified directory and all objects within it.
If the prefix is not specified or is set to NULL in the following sample code, all objects in the bucket are deleted. Exercise caution when you specify a prefix for a delete operation.
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; 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 of the names of the objects that you want to delete. If you want to delete all objects whose names contain the src prefix, set the prefix to src. After you set the prefix to src, all non-directory objects whose names contain the src prefix, the src directory, and all objects in the src directory are deleted. String prefix = "src"; // If you want to delete only the src directory and all objects in the directory, set the prefix to src/. // String prefix = "src/"; // 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 associated 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 all objects whose names contain the specified prefix and delete the objects. String nextMarker = null; ObjectListing objectListing = null; do { ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName) .withPrefix(prefix) .withMarker(nextMarker); objectListing = ossClient.listObjects(listObjectsRequest); if (objectListing.getObjectSummaries().size() > 0) { List<String> keys = new ArrayList<String>(); for (OSSObjectSummary s : objectListing.getObjectSummaries()) { System.out.println("key name: " + s.getKey()); keys.add(s.getKey()); } DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url"); DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest); List<String> deletedObjects = deleteObjectsResult.getDeletedObjects(); try { for(String obj : deletedObjects) { String deleteObj = URLDecoder.decode(obj, "UTF-8"); System.out.println(deleteObj); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } 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(); } } } }
FAQ
How do I check whether the object that I delete using OSS SDK for Java is actually deleted?
When you use the deleteObject
method of OSSClient
in the OSS SDK for Java to delete a single object, the object is considered deleted if no exception is returned. To confirm that the object is deleted, you can call the doesObjectExist
method of OSSClient
to check whether the object exists. If the method returns false
, the object has been deleted. For more information, see Determine whether an object exists (Java SDK).
References
Delete a single object
For more information about the API operation for deleting a single object, see DeleteObject.
Delete multiple objects
For the complete sample code for deleting multiple objects, visit GitHub.
For more information about the API operation for deleting multiple objects, see DeleteMultipleObjects.