Spring Boot Read File from resources using ResourceLoader

Tags: Spring Boot Resource ResourceLoader FileCopyUtils

Introduction

In this Spring Boot tutorial, we learn how to read resource files located in the resources folder in a Spring Boot application using ResourceLoader class.

Create New Spring Boot Project

Open Spring Tool Suite IDE, select menu File > New > Spring Starter Project.

On the New Spring Starter Project popup input new project information as below and click Next.

  • Name: spring-boot-resourceloader
  • Group: dev.simplesolution
  • Artifact: spring-boot-resourceloader
  • Version: 1.0.0
  • Description: Spring Boot Read File from resources
  • Package: dev.simplesolution

Spring Boot Read File from resources using ResourceLoader

On the New Spring Starter Project Dependencies popup click Finish.

Spring Boot Read File from resources using ResourceLoader

You can also creating new Spring Boot project using Spring initializr online tool at start.spring.io

Create Sample File in resources folder for Testing

Add a new text file to the resources folder named data.txt with content as below for testing purposes.

/src/main/resources/data.txt

data line 1
data line 2
data line 3

How to use ResourceLoader class to read file from resources folder

Create a new class named TestReadFile and use ResourceLoader class to read data.txt file then log the file content as the following code.

TestReadFile.java

package dev.simplesolution;

import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

@Component
public class TestReadFile implements CommandLineRunner {
	
	private Logger logger = LoggerFactory.getLogger(TestReadFile.class);
	
	@Autowired
	private ResourceLoader resourceLoader;

	@Override
	public void run(String... args) throws Exception {
		Resource resource = resourceLoader.getResource("classpath:data.txt");
		InputStream inputStream = resource.getInputStream();
		byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);
		String outputString = new String(fileData);
		
		logger.info("data.txt file content:");
		logger.info(outputString);
		
	}

}

Run the application, we can see the log messages showing the file content.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.3)

2021-03-03 01:11:53.341  INFO 4700 --- [           main] d.s.SpringBootResourceloaderApplication  : Starting SpringBootResourceloaderApplication using Java 1.8.0_231 on SS with PID 4700 (D:\SimpleSolution\spring-boot-resourceloader\bin\main started by SS in D:\SimpleSolution\spring-boot-resourceloader)
2021-03-03 01:11:53.342  INFO 4700 --- [           main] d.s.SpringBootResourceloaderApplication  : No active profile set, falling back to default profiles: default
2021-03-03 01:11:53.622  INFO 4700 --- [           main] d.s.SpringBootResourceloaderApplication  : Started SpringBootResourceloaderApplication in 0.479 seconds (JVM running for 1.365)
2021-03-03 01:11:53.625  INFO 4700 --- [           main] dev.simplesolution.TestReadFile          : data.txt file content:
2021-03-03 01:11:53.625  INFO 4700 --- [           main] dev.simplesolution.TestReadFile          : data line 1
data line 2
data line 3

Final Application Source Code

At this step we have the complete Spring Boot project with code structure as below.

Spring Boot Read File from resources using ResourceLoader

Download Source Code

The source code in this article can be found at: github.com/simplesolutiondev/spring-boot-resourceloader

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-resourceloader.git

or download at:

Download Source Code

Happy Coding 😊