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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Top 10 Pillars of Zero Trust Networks
  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • VPN Architecture for Internal Networks

Trending

  • Top 10 Pillars of Zero Trust Networks
  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • VPN Architecture for Internal Networks
  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.

Sandesh Shetty user avatar by
Sandesh Shetty
·
Jan. 10, 20 · Tutorial
Like (5)
Save
Tweet
Share
23.36K 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

Put a Spring in Your Step: Spring Framework Tutorials

A Guide to Spring Framework Annotations

Spring Framework Spring Boot File system

Opinions expressed by DZone contributors are their own.

Trending

  • Top 10 Pillars of Zero Trust Networks
  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • VPN Architecture for Internal Networks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: