AWS Developer Tools Blog

Closeable S3Objects

The com.amazonaws.services.s3.model.S3Object class now implements the Closeable interface (AWS SDK for Java 1.4.8 onwards). This allows you to use it as a resource in a try-with-resources statement. S3Object contains an S3ObjectInputStream that lets you stream down your data over the HTTP connection from Amazon S3. Since the HTTP connection is open and waiting, it’s important to read the stream quickly after calling getObject and to remember to close the stream so that the HTTP connection can be released properly. With the new Closeable interface, it’s even easier to ensure that you’re properly handling those HTTP connection resources.

The following snippet demonstrates how simple it is to use S3Object with a try-with-resources statement.

try (S3Object object = s3.getObject(bucket, key)) {
    System.out.println("key: " + object.getKey());
    System.out.println("data: " + dumpStream(object.getObjectContent());
} catch (Exception e) {
    System.out.println("Unable to download object from Amazon S3: " + e);
}