DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Trending

  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot: Reading Resources

Spring Boot: Reading Resources

Learn how to read files from the resources folder in a Spring Boot application.

By 
Sandesh Shetty user avatar
Sandesh Shetty
·
Jan. 10, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
24.9K Views

Join the DZone community and get the full member experience.

Join For Free

Learn how to read files from the resources folder in a Spring Boot application.

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.

Image title

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.

Java
 




xxxxxxxxxx
1


 
1
public void readFolderFromJar() throws Exception {
2
    String relativePath = "metafiles";
3
    URI resource = getClass().getClassLoader().getResource(relativePath).toURI();
4
    try (FileSystem jarFileSystem = FileSystems.newFileSystem(resource, Collections.emptyMap())) {
5
        String[] jarPath = resource.toString().split("!", 2);
6
        String jarReference = jarPath[1].replace("!", "");
7
        readContent(jarFileSystem.getPath(jarReference));
8
    }
9
}



Recursively Traverse

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. 

Java
 




xxxxxxxxxx
1
39


 
1
public void readContent(Path path)
2
    {
3
        try
4
        {
5
            Stream<Path> list = Files.list(path);
6
            List<Path> paths = list.parallel().collect(Collectors.toList());
7
            paths.stream().parallel().forEach(filePath -> {
8
                if (Files.isDirectory(filePath))
9
                {
10
                    readContent(filePath);
11
                }
12
                else
13
                {
14
                    try
15
                    {
16
                        String fileName = filePath.toString().split("classes")[1];
17
                        String content = readFile(filePath);
18
                        logger.debug("File: "+fileName+": Content: "+content);
19
                    }
20
                    catch (Exception e)
21
                    {
22
                        logger.error("Unable to read file " + e.getMessage());
23
                    }
24
                }
25
            });
26
        }
27
        catch (Exception e)
28
        {
29
            logger.error("Unable to read file " + e.getMessage());
30
        }
31
    }
32
Read content
33
Read content of files from path using Files.readAllBytes. 
34

          
35
   private String readFile(Path path) throws IOException
36
    {
37
        byte[] encoded = Files.readAllBytes(path);
38
        return  new String(encoded, Charset.forName("UTF-8"));
39
    }



Test Run

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!

Further Reading

Working With Resources in Spring

A Guide to Spring Framework Annotations

Spring Framework Spring Boot File system

Opinions expressed by DZone contributors are their own.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!