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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

  • Securing the AI Host: Spring AI MCP Server Communication With API Keys
  • MuleSoft MCP and A2A in Production: What 17 Recipes Reveal
  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  • The Serverless Illusion: When “Pay for What You Use” Becomes Expensive
  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
25.6K 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

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook