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:

So sánh HashSet, LinkedHashSet và TreeSet trong Java
Java Program to Find Whether a Path Exists Between 2 Given Nodes
HttpClient 4 Cookbook
Chuyển đổi giữa các kiểu dữ liệu trong Java
Java Program to Represent Graph Using Adjacency List
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Feign – Tạo ứng dụng Java RESTful Client
Java Program to Find the Shortest Path Between Two Vertices Using Dijkstra’s Algorithm
Hướng dẫn Java Design Pattern – Visitor
Java Program to Optimize Wire Length in Electrical Circuit
A Comparison Between Spring and Spring Boot
StringBuilder vs StringBuffer in Java
Spring Boot - Google Cloud Platform
Removing all Nulls from a List in Java
Lập trình đa luồng trong Java (Java Multi-threading)
Zipping Collections in Java
Spring Boot - Service Components
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Spring MVC Content Negotiation
Send an email with an attachment
Java Program to Implement Skew Heap
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Spring Boot - Exception Handling
Notify User of Login From New Device or Location
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Introduction to Spring Data REST
Anonymous Classes in Java
Spring Security Remember Me
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Java 8 Stream findFirst() vs. findAny()
Intro to Inversion of Control and Dependency Injection with Spring