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
Newsletter
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

  • How to Format Articles for DZone
  • Fix the Target, Precompute Once: A Backend-Free Word-Ladder Solver With a BFS Distance Field
  • How Kestra Unifies Enterprise Workflow Orchestration and Agentic AI
  • AI Agents and Frontier Models: Insights From The Neuron

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jan. 10, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
25.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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