Spring Boot
read file
resources folder
Java
tutorial

Read file from resources folder in Spring Boot

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Spring Boot applications, reading files from various sources is a common requirement. This article will focus on reading files from the resources folder, which is a standard directory structure used for storing application resources such as configuration files, static assets, and templates.

Understanding the Resources Folder

The resources folder in a Spring Boot application is typically located inside the src/main/resources directory. When the application is packaged, these resources are included in the classpath, and you can easily access them using various utilities provided by Spring Framework.

Accessing Files from the Resources Folder

Spring Boot provides several ways to read files from the resources folder. Here we'll discuss three primary approaches:

  1. Using ResourceLoader
  2. Using @Value annotation with ResourceLoaderAware
  3. Using Spring's ResourceUtils

Using ResourceLoader

ResourceLoader is an interface provided by Spring that allows you to obtain a Resource from different sources. Here is an example of how to use ResourceLoader to read a file:

java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.core.io.Resource;
3import org.springframework.core.io.ResourceLoader;
4import org.springframework.stereotype.Service;
5import java.io.IOException;
6import java.nio.file.Files;
7import java.nio.file.Paths;
8
9@Service
10public class ResourceLoaderService {
11
12    private final ResourceLoader resourceLoader;
13
14    @Autowired
15    public ResourceLoaderService(ResourceLoader resourceLoader) {
16        this.resourceLoader = resourceLoader;
17    }
18
19    public String readFileFromResources(String filePath) throws IOException {
20        Resource resource = resourceLoader.getResource("classpath:" + filePath);
21        byte[] fileData = Files.readAllBytes(Paths.get(resource.getURI()));
22        return new String(fileData);
23    }
24}

Using @Value Annotation

Another common way to read a file is by using the @Value annotation in combination with ResourceLoaderAware. Here's how you can do it:

java
1import org.springframework.beans.factory.annotation.Value;
2import org.springframework.context.ResourceLoaderAware;
3import org.springframework.core.io.Resource;
4import org.springframework.core.io.ResourceLoader;
5import org.springframework.stereotype.Service;
6import java.io.IOException;
7import java.nio.file.Files;
8
9@Service
10public class ValueAnnotationService implements ResourceLoaderAware {
11    
12    @Value("classpath:data/file.txt")
13    private Resource resource;
14    
15    private ResourceLoader resourceLoader;
16
17    @Override
18    public void setResourceLoader(ResourceLoader resourceLoader) {
19        this.resourceLoader = resourceLoader;
20    }
21    
22    public String readFile() throws IOException {
23        return Files.readString(resource.getFile().toPath());
24    }
25}

Using Spring's ResourceUtils

ResourceUtils is a utility class in Spring that can be used to get a URL or File reference to resources. Here's an example:

java
1import org.springframework.util.ResourceUtils;
2import java.io.File;
3import java.io.IOException;
4import java.nio.file.Files;
5
6public class ResourceUtilsExample {
7
8    public String readFile(String filePath) throws IOException {
9        File file = ResourceUtils.getFile("classpath:" + filePath);
10        return Files.readString(file.toPath());
11    }
12}

Configuration Files

In some cases, you may need to define file paths in application properties for dynamic loading. You can use the following configuration:

properties
file.path=classpath:data/file.txt

And access it using:

java
@Value("${file.path}")
private Resource fileResource;

Handling Exceptions

When reading files, it's important to handle exceptions properly, such as IOException for input/output errors and potentially missing resources.

Summary Table

ApproachDescriptionUse Case
ResourceLoaderLoads resources using Resource interfaceDynamic resource loading
@Value with ResourceLoaderAwareSimplifies resource injection using @Value annotationSpring DI advantage
ResourceUtilsProvides simple utility methods to access resources as File or URLWhen direct file access is required
Configuration via PropertiesDynamic file path configuration using properties fileConfiguration-driven access

Conclusion

Reading files from the resources folder in a Spring Boot application is flexible and straightforward. By leveraging Spring's built-in features such as ResourceLoader, @Value, and ResourceUtils, you can efficiently manage application resources. Understanding these approaches will help you choose the right method based on your specific requirements.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.