Objects cannot be directly renamed. To rename an object in the bucket, you can call the CopyObject operation to copy the source object to the destination object and call the DeleteObject operation to delete the source object.
Sample code
The following sample code provides examples on how to rename an object named srcobject.txt in the examplebucket bucket to destobject.txt.
// Specify the name of the bucket.
String bucketName = "examplebucket";
// Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcobject.txt.
String sourceObjectKey = "srcobject.txt";
// Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destobject.txt.
String objectKey = "destobject.txt";
try {
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucketName, sourceObjectKey, bucketName, objectKey);
oss.copyObject(copyObjectRequest);
// Delete the srcobject.txt object.
DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, sourceObjectKey);
oss.deleteObject(deleteObjectRequest);
} catch (ClientException e) {
// Handle client-side exceptions, such as network errors.
e.printStackTrace();
} catch (ServiceException e) {
// Handle server-side exceptions.
Log.e("RequestId", e.getRequestId());
Log.e("ErrorCode", e.getErrorCode());
Log.e("HostId", e.getHostId());
Log.e("RawMessage", e.getRawMessage());
}
Directories in a bucket also cannot be directly renamed. To rename a directory in a bucket, you can follow the preceding example to rename the subdirectories and objects in the directory one by one.
References
For more information about the API operations that you can call to rename an object, see CopyObject and DeleteObject.
For more information about how to initialize an OSSClient instance, see Initialization.