Determine the existence and content type of an object in an Amazon S3 bucket using an AWS SDK - Amazon Simple Storage Service

Determine the existence and content type of an object in an Amazon S3 bucket using an AWS SDK

The following code examples show how to determine the existence and content type of an object in an S3 bucket.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

Determine the content type of an object.

public static void getContentType (S3Client s3, String bucketName, String keyName) { try { HeadObjectRequest objectRequest = HeadObjectRequest.builder() .key(keyName) .bucket(bucketName) .build(); HeadObjectResponse objectHead = s3.headObject(objectRequest); String type = objectHead.contentType(); System.out.println("The object content type is "+type); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

Get the restore status of an object.

public static void checkStatus(S3Client s3, String bucketName, String keyName) { try { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucketName) .key(keyName) .build(); HeadObjectResponse response = s3.headObject(headObjectRequest); System.out.println("The Amazon S3 object restoration status is "+response.restore()); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • For API details, see HeadObject in AWS SDK for Java 2.x API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectExistsWrapper attr_reader :object # @param object [Aws::S3::Object] An Amazon S3 object. def initialize(object) @object = object end # Checks whether the object exists. # # @return [Boolean] True if the object exists; otherwise false. def exists? @object.exists? rescue Aws::Errors::ServiceError => e puts "Couldn't check existence of object #{@object.bucket.name}:#{@object.key}. Here's why: #{e.message}" false end end # Replace bucket name and object key with an existing bucket and object that you own. def run_demo bucket_name = "doc-example-bucket" object_key = "my-object.txt" wrapper = ObjectExistsWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) exists = wrapper.exists? puts "Object #{object_key} #{exists ? 'does' : 'does not'} exist." end run_demo if $PROGRAM_NAME == __FILE__
  • For API details, see HeadObject in AWS SDK for Ruby API Reference.

For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions.