Open In App

Read file from Resources Folder in Spring Boot

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Spring Boot is a framework for handling web applications, and it is easy to create stand-alone applications. The Spring Boot framework is an open-source Java-based framework mostly used for creating microservices. In this article, we will discuss how to read file from the resources folder in Spring Boot.

The Resource folder is available in the Spring Project structure and we have provided a related image below for a better understanding of the concept. In the Resource folder, we have created one Text file to read the data.

Prerequisites:

  • Spring Boot Framework
  • File Handling
  • Error Handling
  • Rest APIs
  • Spring Boot project creation ( Spring starter Project)

Resource Folder:

We can see the resource folder in the project structure below.


Resource Folder in Project Structure


Example Text File:

We have created one text file in Resource folder that is File1.txt and we have some data in that file.

Example text file

Steps to Implement Read file from resources folder

Here we will create a simple Spring Boot application to Read file from resources folder by using RestController API end point. When we hit that API in browser, we can be able to see the text in file on the web browser as output.

Step 1: Create a Spring Boot project by using Spring initializer with required project dependencies. Below is the dependencies that are used in this Project.

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}


Step 2: After successfully creation of Spring Project, now create a java class in main package of the project.

  • In the above, we have provided the project Folder structure, in that we can find this.
  • Then develop the required logic.
  • This class is used for creating API end points.
  • When we hit this end point on the web browser, we see can the output, means reading text from file in resources folder.
  • Here, we have created readfile API by using @GetMapping Annotation.
  • In this method, we called readFileFromResources() which is created in FileService class.
Java
package com.read.file.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;

@RestController
public class FileController {
    
    @Autowired
    private FileService fileService;

    // API endpoint to read a file from the resources folder
    @GetMapping("/readfile")
    public String readFile() {
        try {
            // Call the service method to read the file
            return fileService.readFileFromResources("File1.txt");
        } catch (IOException e) {
            // Print stack trace if an exception occurs
            e.printStackTrace();
            // Return an error message if reading the file fails
            return "Error occurred while reading file.";
        }
    }

}


Step 3: After this, we have created one more java class in the main package in the project folder with name FileService.

  • In this class we can develop the core logic means we can develop how to Read file from resources folder in Spring Boot by using ResourceLoader.
  • The ResourceLoader is interface which is used for load resources from the classpath, file system or from any other location.
  • Here, we have created one method that is readFileFromResources() which takes one String value that is file name.
  • Then we have created object for Resource after this by using getResource().
  • This method is available in ResourceLoader interface.
  • Finally by using InputStream, BufferedReader, StringBuilder, we read data from file which is located in resource folder then it print that text on web page.
Java
package com.read.file.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Service
public class FileService {

    // Autowiring ResourceLoader for loading resources
    @Autowired
    private ResourceLoader resourceLoader;

    // Method to read a file from the resources folder
    public String readFileFromResources(String filename) throws IOException {
        // Getting the resource using the ResourceLoader
        Resource resource = resourceLoader.getResource("classpath:" + filename);
        // Opening an InputStream to read the content of the resource
        InputStream inputStream = resource.getInputStream();
        // Creating a BufferedReader to read text from the InputStream efficiently
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        // StringBuilder to accumulate the lines read from the file
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        // Reading each line from the file and appending it to the StringBuilder
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        // Closing the BufferedReader
        reader.close();
        // Returning the contents of the file as a string
        return stringBuilder.toString();
    }

}


Step 4: After completion of developing the logic, run this project as Spring Boot App on 8080 port.

Application Runs


Step 5: After this, open any web browser, then hit the below Rest API. Then we will get the below output.

http://localhost:8080/readfile

Output:

Read File Output




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads