Last Updated on 03 January 2022   |   Print Email
In this AWS Java SDK article, I’d like share some Java code examples about file download from a bucket on Amazon S3 programmatically. You can use the code example to add S3 file download function to your application.I suppose that you already have AWS SDK for Java set up on your computer. If not, follow this guide: How to setup AWS SDK for Java for Amazon S3 Development.Below is the code of a Java console program that downloads a file from a bucket on S3, and then saves the file on disk:
To run this program, you must specify exactly the bucket name on your AWS account, the object key of file, and the AWS credentials you’re using has at least read permission on the file.In this example, the object key looks like it is directly underneath the bucket. And the file will be saved in the current directory (same as application’s directory). The file name is as same as the object key.If you use a key that looks like a directory path, consider the following example:
For handling exception, consider to catch NoSuchKeyException, InvalidObjectStateException, AwsServiceException, SdkClientException, and S3Exception which can be thrown by the S3Client.getObject() method.That’s a couple of examples for downloading a file from a bucket on Amazon S3. I hope you find it useful. To see the coding in action, watch the following video:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.