Spring Boot Read File from resources using ClassPathResource
Tags: Spring Boot Resource ClassPathResource FileCopyUtils
Introduction
In this Spring Boot tutorial, we learn how to read files located in the resources folder in a Spring Boot application using ClassPathResource 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-classpathresource
- Group: dev.simplesolution
- Artifact: spring-boot-classpathresource
- Version: 1.0.0
- Description: Spring Boot Read File from resources
- Package: dev.simplesolution
On the New Spring Starter Project Dependencies popup click Finish.
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.json with content as below for testing purposes.
/src/main/resources/data.json
{
"firstName": "Simple",
"lastName": "Solution"
}
How to use ClassPathResource class to read file from resources folder
Create a new class named TestReadFile and use ClassPathResource class to read data.json file then print the log message file content as following code.
TestReadFile.java
package dev.simplesolution;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
@Component
public class TestReadFile implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(SpringBootClasspathresourceApplication.class);
@Override
public void run(String... args) throws Exception {
// Read file from resources folder
Resource resource = new ClassPathResource("data.json");
InputStream inputStream = resource.getInputStream();
byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);
String outputString = new String(fileData);
logger.info("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 00:25:21.108 INFO 12092 --- [ main] s.SpringBootClasspathresourceApplication : Starting SpringBootClasspathresourceApplication using Java 1.8.0_231 on SS with PID 12092 (D:\SimpleSolution\spring-boot-classpathresource\bin\main started by SS in D:\SimpleSolution\spring-boot-classpathresource)
2021-03-03 00:25:21.110 INFO 12092 --- [ main] s.SpringBootClasspathresourceApplication : No active profile set, falling back to default profiles: default
2021-03-03 00:25:21.387 INFO 12092 --- [ main] s.SpringBootClasspathresourceApplication : Started SpringBootClasspathresourceApplication in 0.481 seconds (JVM running for 1.364)
2021-03-03 00:25:21.389 INFO 12092 --- [ main] s.SpringBootClasspathresourceApplication : File content:
2021-03-03 00:25:21.389 INFO 12092 --- [ main] s.SpringBootClasspathresourceApplication : {
"firstName": "Simple",
"lastName": "Solution"
}
Final Application Source Code
At this step we have the complete Spring Boot project with code structure as below.
Download Source Code
The source code in this article can be found at: github.com/simplesolutiondev/spring-boot-classpathresource
or clone at:
git clone https://github.com/simplesolutiondev/spring-boot-classpathresource.git
or download at:
Happy Coding 😊