All Products
Search
Document Center

Object Storage Service:Prevent overwriting objects with the same name (Java SDK V1)

Last Updated:Nov 25, 2025

By default, a new object overwrites an existing object that has the same name if you have the required access permissions. This topic describes how to prevent this behavior by setting the x-oss-forbid-overwrite request header for simple uploads, object copies, and multipart uploads.

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 OSS 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.

Simple upload

The following code shows how to prevent an object with the same name from being overwritten during a simple upload:

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.ByteArrayInputStream;

public class Demo {
    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the bucket name.
        String objectName = "exampledir/object";
        String content = "Hello OSS!";
        // Specify the region where the bucket is located. For example, if the bucket is 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 instance is no longer needed.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create a PutObjectRequest object.
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));

            // Specify whether to overwrite an object with the same name during the upload.
            // If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
            // If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
            // If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name already exists, the program reports an error.
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader("x-oss-forbid-overwrite", "true");
            putObjectRequest.setMetadata(metadata);

            // Upload the file.
            ossClient.putObject(putObjectRequest);
        } 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();
            }
        }
    }
}

Copy files

  • Copy a small object using CopyObjectRequest

    The following code shows how to prevent an object with the same name from being overwritten when you copy a small object using CopyObjectRequest:

    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 {
            // This example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the source bucket name.
            String sourceBucketName = "srcexamplebucket";
            // Specify the full path of the source object. The full path cannot contain the bucket name.
            String sourceObjectName = "srcexampleobject.txt";
            // Specify the destination bucket name. The destination bucket must be in the same region as the source bucket.
            String destinationBucketName = "desexamplebucket";
            // Specify the full path of the destination object. The full path cannot contain the bucket name.
            String destinationObjectName = "desexampleobject.txt";
            // Specify the region where the bucket is located. For example, if the bucket is 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 instance is no longer needed.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a CopyObjectRequest object.
                CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
    
                // Set new object metadata.
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType("text/html");
                // Specify whether to overwrite an object with the same name during the copy operation.
                // If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
                // If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
                // If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name already exists, the program reports an error.
                metadata.setHeader("x-oss-forbid-overwrite", "true");
                copyObjectRequest.setNewObjectMetadata(metadata);
    
                // Copy the object.
                CopyObjectResult result = ossClient.copyObject(copyObjectRequest);
                System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
            } 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();
                }
            }
        }
    }
  • Copy a large object

    The following code shows how to prevent an object with the same name from being overwritten when you copy a large object using multipart copy:

    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.ArrayList;
    import java.util.List;
    
    public class Demo {
        public static void main(String[] args) throws Exception {
            // This example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run this code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the source bucket name.
            String sourceBucketName = "srcexamplebucket";
            // Specify the full path of the source object. The full path cannot contain the bucket name.
            String sourceObjectName = "srcexampleobject.txt";
            // Specify the destination bucket name. The destination bucket must be in the same region as the source bucket.
            String destinationBucketName = "desexamplebucket";
            // Specify the full path of the destination object. The full path cannot contain the bucket name.
            String destinationObjectName = "desexampleobject.txt";
            // Specify the region where the bucket is located. For example, if the bucket is 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 instance is no longer needed.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceObjectName);
                // Get the size of the object to copy.
                long contentLength = objectMetadata.getContentLength();
    
                // Set the part size to 10 MB.
                long partSize = 1024 * 1024 * 10;
    
                // Calculate the total number of parts.
                int partCount = (int) (contentLength / partSize);
                if (contentLength % partSize != 0) {
                    partCount++;
                }
                System.out.println("total part count:" + partCount);
    
                // Initialize the copy task. You can specify the metadata of the destination object in InitiateMultipartUploadRequest.
                InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(destinationBucketName, destinationObjectName);
                // Specify whether to overwrite an object with the same name during the copy operation.
                // If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
                // If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
                // If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name already exists, the program reports an error.
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setHeader("x-oss-forbid-overwrite", "true");
                initiateMultipartUploadRequest.setObjectMetadata(metadata);
    
                InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest);
                String uploadId = initiateMultipartUploadResult.getUploadId();
    
                // Copy parts.
                List<PartETag> partETags = new ArrayList<PartETag>();
                for (int i = 0; i < partCount; i++) {
                    // Calculate the size of each part.
                    long skipBytes = partSize * i;
                    long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes;
    
                    // Create an UploadPartCopyRequest. You can specify conditions in UploadPartCopyRequest.
                    UploadPartCopyRequest uploadPartCopyRequest =
                            new UploadPartCopyRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
                    uploadPartCopyRequest.setUploadId(uploadId);
                    uploadPartCopyRequest.setPartSize(size);
                    uploadPartCopyRequest.setBeginIndex(skipBytes);
                    uploadPartCopyRequest.setPartNumber(i + 1);
                    UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);
    
                    // Save the returned part ETag to partETags.
                    partETags.add(uploadPartCopyResult.getPartETag());
                }
    
                // Complete the multipart copy task.
                CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
                        destinationBucketName, destinationObjectName, uploadId, partETags);
    
                // Specify whether to overwrite an object with the same name during the copy operation.
                // If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
                // If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
                // If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name already exists, the program reports an error.
                completeMultipartUploadRequest.addHeader("x-oss-forbid-overwrite", "true");
    
                ossClient.completeMultipartUpload(completeMultipartUploadRequest);
            } 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();
                }
            }
        }
    }

Multipart upload

The following code shows how to prevent an object with the same name from being overwritten during a multipart upload:

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.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Replace it with your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. For example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the bucket name.
        String objectName = "exampledir/object";
        // Specify the region where the bucket is located. For example, if the bucket is 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 instance is no longer needed.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create an InitiateMultipartUploadRequest object.
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);

            // Specify whether to overwrite an object with the same name during the multipart upload.
            // If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
            // If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
            // If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name already exists, the program reports an error.
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader("x-oss-forbid-overwrite", "true");
            request.setObjectMetadata(metadata);

            // Initialize the multipart upload.
            InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
            // The upload ID is returned. It is the unique identifier of the multipart upload event. You can use this ID to perform related operations, such as aborting or querying the multipart upload.
            String uploadId = upresult.getUploadId();

            // partETags is a collection of PartETag objects. A PartETag consists of the ETag and part number of a part.
            List<PartETag> partETags =  new ArrayList<PartETag>();
            // Calculate the number of parts.
            final long partSize = 1 * 1024 * 1024L;   // 1 MB
            final File sampleFile = new File("<localFile>");
            long fileLength = sampleFile.length();
            int partCount = (int) (fileLength / partSize);
            if (fileLength % partSize != 0) {
                partCount++;
            }
            // Upload parts in a loop.
            for (int i = 0; i < partCount; i++) {
                long startPos = i * partSize;
                long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
                InputStream instream = new FileInputStream(sampleFile);
                // Skip the uploaded parts.
                instream.skip(startPos);
                UploadPartRequest uploadPartRequest = new UploadPartRequest();
                uploadPartRequest.setBucketName(bucketName);
                uploadPartRequest.setKey(objectName);
                uploadPartRequest.setUploadId(uploadId);
                uploadPartRequest.setInputStream(instream);
                // Set the part size. The minimum size of each part is 100 KB, except for the last part.
                uploadPartRequest.setPartSize(curPartSize);
                // Set the part number. Each uploaded part has a part number that ranges from 1 to 10,000. If the part number is outside this range, OSS returns an InvalidArgument error code.
                uploadPartRequest.setPartNumber( i + 1);
                // Parts do not need to be uploaded in sequence and can be uploaded from different clients. OSS combines the parts into a complete object based on their part numbers.
                UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
                // After each part is uploaded, the OSS response contains a PartETag. The PartETag is saved to partETags.
                partETags.add(uploadPartResult.getPartETag());
            }


            // Create a CompleteMultipartUploadRequest object.
            // To complete the multipart upload, you must provide all valid partETags. After OSS receives the submitted partETags, it verifies each part. When all parts are verified, OSS combines them into a complete object.
            CompleteMultipartUploadRequest completeMultipartUploadRequest =
                    new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);

            // Specify whether to overwrite an object with the same name during the multipart upload.
            // If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
            // If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
            // If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name already exists, the program reports an error.
            completeMultipartUploadRequest.addHeader("x-oss-forbid-overwrite", "true");

            // Complete the upload.
            CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
        } 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();
            }
        }
    }
}

References

  • For the complete sample code that shows how to prevent objects with the same name from being overwritten in various upload scenarios, see the GitHub example.

  • For more information about the API operation for simple upload, see PutObject.

  • For more information about the API operation for copying an object, see CopyObject.

  • For more information about the API operations for multipart upload, see InitiateMultipartUpload and CompleteMultipartUpload.