How to download s3 object directly into memory in java

Manisha  picture Manisha · Nov 1, 2012 · Viewed 22.7k times · Source

Is it possible to download S3object in Java directly into memory and get it removed when i'm done with the task?

Answer

Zach Musgrave picture Zach Musgrave · Nov 1, 2012

Use the AWS SDK for Java and Apache Commons IO as such:

//import org.apache.commons.io.IOUtils

AmazonS3 s3  = new AmazonS3Client(credentials);  // anonymous credentials are possible if this isn't your bucket
S3Object object = s3.getObject("bucket", "key"); 
byte[] byteArray = IOUtils.toByteArray(object.getObjectContent());

Not sure what you mean by "get it removed", but IOUtils will close the object's input stream when it's done converting it to a byte array. If you mean you want to delete the object from s3, that's as easy as:

s3.deleteObject("bucket", "key");