Search code examples
javaamazon-web-servicesamazon-s3aws-java-sdk

AWS Java SDK: check if an object exists with a specific version in an S3 bucket


I know there is a doesObjectExist method to check if an object exists in a specified bucket, but how do I check if an object with a specific version exists in an S3 bucket?

I want to call doesObjectExist(bucketName, objectName, s3Version).

Is there any way I can do this, or do I need to call listVersions first and check if the version exists using the VersionListing? This approach seems a lot more verbose.


Solution

  • There is no one step check in the current API. You could try using something like

    s3Client.getObjectMetadata(
      new GetObjectMetadataRequest(bucketName, key, versionId)
    )
    

    But then I don't see any reliable way to know when such object doesn't exist (because there's no a special "object doesn't exist" exception for such case). So after it fails you should check that this object exists with doesObjectExist. Or another way round: check that it exists, then query the metadata with version, if it exists but the metadata request fails, this version of the object doesn't exist.