Spring Boot
Read File
Resources Folder
Java
File Handling

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

Overview

Spring Boot is a widely used framework for building Java-based web applications that are both scalable and production-ready. One common requirement in such applications is reading files from the resources folder. This article provides a comprehensive guide on how to achieve this in a Spring Boot application, including code examples and technical explanations.

Spring Boot Resource Folder

In a Spring Boot application, the resources folder is typically where the non-Java files such as properties files, XML configurations, text files, and images are stored. During the build process, these files are packaged into the JAR or WAR file under the BOOT-INF/classes directory, making them accessible at runtime.

Accessing Files in the Resources Folder

Using ResourceLoader

Spring provides the ResourceLoader interface as part of its core framework. This interface can be used to access resources. Here's 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;
5
6import java.io.BufferedReader;
7import java.io.InputStreamReader;
8import java.nio.charset.StandardCharsets;
9
10@Service
11public class ResourceService {
12
13    @Autowired
14    private ResourceLoader resourceLoader;
15
16    public void readResourceFile(String resourcePath) {
17        try {
18            Resource resource = resourceLoader.getResource(resourcePath);
19            BufferedReader reader = new BufferedReader(
20                new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
21                
22            reader.lines().forEach(System.out::println);
23        } catch (Exception e) {
24            e.printStackTrace();
25        }
26    }
27}

In this example, resourceLoader.getResource("classpath:filename.txt") is used to access the file located in the resources directory.

Using @Value Annotation

Another approach is to utilize the Spring @Value annotation, which is particularly helpful for reading file contents directly as a string:

java
1import org.springframework.beans.factory.annotation.Value;
2import org.springframework.stereotype.Service;
3
4import java.nio.file.Files;
5import java.nio.file.Paths;
6
7@Service
8public class ValueAnnotationService {
9
10    @Value("classpath:filename.txt")
11    private org.springframework.core.io.Resource resourceFile;
12
13    public void printFileContent() {
14        try {
15            String content = new String(Files.readAllBytes(Paths.get(resourceFile.getURI())));
16            System.out.println(content);
17        } catch (Exception e) {
18            e.printStackTrace();
19        }
20    }
21}

This method simplifies file reading processes for when the file content is needed as a single string.

Using ResourceUtils

For cases where you need a File object, ResourceUtils.getFile() can be employed:

java
1import org.springframework.util.ResourceUtils;
2
3import java.io.File;
4import java.nio.file.Files;
5import java.util.List;
6
7public class FileService {
8
9    public void readFile() {
10        try {
11            File file = ResourceUtils.getFile("classpath:filename.txt");
12            List<String> lines = Files.readAllLines(file.toPath());
13            lines.forEach(System.out::println);
14        } catch (Exception e) {
15            e.printStackTrace();
16        }
17    }
18}

Note that ResourceUtils.getFile() throws FileNotFoundException if the file cannot be resolved as a file in the file system.

Table: Key Techniques for Reading Resources

TechniqueDescriptionProsCons
ResourceLoaderUses Spring's ResourceLoader interface to read files.Flexible and versatile.Requires setup of Spring beans.
@Value AnnotationInjects file content directly via Spring's annotation support.Simple to use; concise code.Mainly for simple cases; less control.
ResourceUtils.getFile()Converts a resource into a Java File object.Works with Java File API.May not work in all environments (e.g., JARs).

Additional Considerations

Handling Different Environments

When working with a Spring Boot application in different environments (e.g., dev, test, prod), resources might be located differently. It's important to consider this in your resource-loading strategy and possibly use environment-specific configurations to handle this.

Exception Handling

Proper exception handling is crucial to ensure that file reading does not cause unexpected application crashes. Consider using custom exceptions and Spring's exception-handling features to manage errors gracefully.

UTF-8 Encoding and Internationalization

When reading text files, always ensure that the correct charset (such as UTF-8) is used to avoid issues with special characters or internationalization.

Unit Testing with Resources

When writing unit tests for components that read resources, consider mocking the resource loader or employing test-specific resources to ensure consistency and reliability in different environments.

Conclusion

Reading files from the resources folder in a Spring Boot application is a common task that can be accomplished in several ways. Understanding the various methods available will help you choose the right approach for your specific needs and context. Whether using ResourceLoader, the @Value annotation, or ResourceUtils.getFile(), each method provides a way to work effectively with application resources.


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.