Getting file size from S3 bucket

Viewed 27522

I am trying to get the file size (content-length) using Amazon S3 JAVA sdk.

public Long getObjectSize(AmazonS3Client amazonS3Client, String bucket, String key)
        throws IOException {
    Long size = null;
    S3Object object = null;
    try {
        object = amazonS3Client.getObject(bucket, key);
        size = object.getObjectMetadata().getContentLength();

    } finally {
        if (object != null) {
            //object.close();
            1. This results in 50 calls (connection pool size) post that I start getting connection pool errors. 
            2. If this line is uncommented it takes hell lot of time to make calls.
        }
    }
    return size;
}

I followed this and this. But not sure what I am doing wrong here. Any help on this?

2 Answers

For v2 of the Amazon S3 Java SDK, try something like this:

HeadObjectRequest headObjectRequest =
        HeadObjectRequest.builder()
          .bucket(bucket)
          .key(key)
          .build();
HeadObjectResponse headObjectResponse =
        s3Client.headObject(headObjectRequest);
Long contentLength = headObjectResponse.contentLength();
Related