Spring Cloud AWS – S3

1. Simple S3 Download

Let’s start by easily accessing files stored on S3:

@Autowired
ResourceLoader resourceLoader;

public void downloadS3Object(String s3Url) throws IOException {
    Resource resource = resourceLoader.getResource(s3Url);
    File downloadedS3Object = new File(resource.getFilename());
 
    try (InputStream inputStream = resource.getInputStream()) {
        Files.copy(inputStream, downloadedS3Object.toPath(), 
          StandardCopyOption.REPLACE_EXISTING);
    }
}

2. Simple S3 Upload

We can also upload files:

public void uploadFileToS3(File file, String s3Url) throws IOException {
    WritableResource resource = (WritableResource) resourceLoader
      .getResource(s3Url);
 
    try (OutputStream outputStream = resource.getOutputStream()) {
        Files.copy(file.toPath(), outputStream);
    }
}

3. S3 URL Structure

The s3Url is represented using the format:

s3://<bucket>/<object>

For example, if a file bar.zip is in the folder foo on a my-s3-bucket bucket, then the URL will be:

s3://my-s3-bucket/foo/bar.zip

And, we can also download multiple objects at once using ResourcePatternResolver and the Ant-style pattern matching:

private ResourcePatternResolver resourcePatternResolver;
 
@Autowired
public void setupResolver(ApplicationContext applicationContext, AmazonS3 amazonS3) {
    this.resourcePatternResolver = 
      new PathMatchingSimpleStorageResourcePatternResolver(amazonS3, applicationContext);
 }

public void downloadMultipleS3Objects(String s3Url) throws IOException {
    Resource[] allFileMatchingPatten = this.resourcePatternResolver
      .getResources(s3Url);
        // ...
    }
}

URLs can contain wildcards instead of exact names.

For example the s3://my-s3-bucket/**/a*.txt URL will recursively look for all text files whose name starts with ‘a‘ in any folder of the my-s3-bucket.

Note that the beans ResourceLoader and ResourcePatternResolver are created at application startup using Spring Boot’s auto-configuration feature.

4. Conclusion

And we’re done – this is a quick and to-the-point introduction to accessing S3 with Spring Cloud AWS.

In the next article of the series, we’ll explore the EC2 support of the framework.

As usual, the examples are available over on GitHub.

Related posts:

Java Program to Implement Hash Tables Chaining with List Heads
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Spring Security Custom AuthenticationFailureHandler
Introduction to Spring MVC HandlerInterceptor
Prevent Cross-Site Scripting (XSS) in a Spring Application
Spring WebClient vs. RestTemplate
Hướng dẫn Java Design Pattern – Builder
Connect through a Proxy
Giới thiệu Google Guice – Injection, Scope
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Queue và PriorityQueue trong Java
How to Remove the Last Character of a String?
Migrating from JUnit 4 to JUnit 5
Dockerizing a Spring Boot Application
Assertions in JUnit 4 and JUnit 5
Predicate trong Java 8
How To Serialize and Deserialize Enums with Jackson
Mệnh đề Switch-case trong java
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Java Program to Check if it is a Sparse Matrix
Hướng dẫn Java Design Pattern – Interpreter
Guide to @ConfigurationProperties in Spring Boot
Java Program to Perform the Unique Factorization of a Given Number
Spring Security Login Page with React
Guava – Join and Split Collections
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Spring MVC Setup with Kotlin
Java Program to Implement Dijkstra’s Algorithm using Set
Java Program to Implement Hash Tree
Apache Commons Collections Bag
Supplier trong Java 8