- Add the
aws-java-sdk
dependency to your project’s build file. If you’re using Maven, add the following dependency to yourpom.xml
file:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.12.88</version>
</dependency>
If you’re using Gradle, add the following dependency to your build.gradle
file:
implementation 'com.amazonaws:aws-java-sdk:1.12.88'
Replace the version number with the latest version available.
- Create an instance of the
AmazonS3
client class from the AWS SDK for Java. You’ll need to provide your AWS access key and secret key, which you can obtain from the AWS console.
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.withRegion(region)
.build();
Replace accessKey
and secretKey
with your AWS access key and secret key, respectively. You’ll also need to specify the AWS region where your S3 bucket is located.
- Use the
AmazonS3
client instance to interact with your S3 bucket. For example, you can upload a file to S3 like this:
String bucketName = "my-bucket";
String key = "path/to/my/file.txt";
File file = new File("path/to/local/file.txt");
s3.putObject(bucketName, key, file);
This code uploads the local file located at path/to/local/file.txt
to the S3 bucket named my-bucket
with the key path/to/my/file.txt
.
- You can also download a file from S3 like this:
String bucketName = "my-bucket";
String key = "path/to/my/file.txt";
S3Object s3Object = s3.getObject(bucketName, key);
InputStream inputStream = s3Object.getObjectContent();
This code retrieves the S3 object with the key path/to/my/file.txt
from the my-bucket
bucket and returns an input stream that you can use to read the contents of the file.
That’s it! With these basic operations, you can connect to AWS S3 storage from Java and perform common file upload and download tasks. Of course, there are many other features and options available in the AWS SDK for Java for working with S3, so be sure to check out the documentation for more information.