Spring Boot: Reading Resources
Learn how to read files from the resources folder in a Spring Boot application.
Join the DZone community and get the full member experience.Join For Free
Reading files from a Spring Boot application is possible through Java 8 NIO API. This article demonstrates how to read files from the resources folder in a Spring Boot application, which is running as a standalone application or inside the Docker container.
You may also like: Working With Resources in Spring
Create a Project
Generate a Gradle or Maven project using the Spring Initializer. Create folder and files inside the resources folder as required.
Create a Pseudo File System
We are trying to read metafiles folder contents from the above structure. We need to convert the file path to URI resource. Create a new file system for URI resource. Since
FileSystem is Closable, we are able to place initialize the
jarFileSystem within the try block.
If the path is a directory, then recursively call
readContent function until we encounter the individual files. Let us use NIO API Files. Files.list lists would list out paths lazily.
Run your Spring Boot project using the traditional approach shown below. Here, resources/metafiles will be part of "jar," and still, we will be able to read the contents of these files.
java -jar demo-0.0.1-SNAPSHOT.jar
Hope you enjoyed!
Opinions expressed by DZone contributors are their own.