Saturday, March 4, 2023

How to read files from the resources folder in Spring Boot? Example Tutorial

Hello everyone, welcome to the blog post. In this article, we are going to take a look at a frequently asked question in spring boot on how to read files from the resources folder. A resource is any file that contains information relevant to your project, including configuration files, picture files, data files, or other types of files. In this article, we will look at various methods and techniques that both spring boot and ordinary Java code allow us to read a file from the resources directory. Our goal is not simply to list these approaches; rather, we will describe each strategy with the help of an example so that, everyone can easily grasp the topic. Without further ado, let's get started. 


5 Ways to Read files from the resources folder in Spring Boot

There are many ways to read a file from the resource folder in Spring Boot but following are the most popular ways to read a file;

Using Spring Resource Interface

o ClassPathResource

o @Value annotation

ResourceLoader

ResourceUtils

We will see each one of them in detail with code example, so that you can use them in your code. In the upcoming sections we will discuss the above-mentioned methods in great detail;

How to read files from the resources folder in Spring Boot? Example Tutorial


1. Using Spring Resource Interface 

The great thing about spring Resource Interface is, it hides the low-level details from its user, but still provides a uniform way to handle every kind of resource that it supports. Let’s first take a look at the interface itself. 

public interface InputStreamSource {

InputStream getInputStream() throws IOException;

}



public interface Resource extends InputStreamSource {

    boolean exists();

    boolean isOpen();

    URL getURL() throws IOException;

    File getFile() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

String getDescription();

}


The above interface has following methods:

exists(): boolean

isOpen(): boolean

getURL(): URL

getFile(): File

createRelative(): Resource

getFilename(): String

getDescription(): String


I’m sure many of you already know we can’t create an object or instance of an interface. Instead, we require a class that provides its implementation. Many classes implement Resource interfaces in Spring, these are UrlReource, FileSystemResource, ClassPathResource, ServletContextResource, and InputStreamResource.

Here we will focus only on one implementation class i.e. ClassPathResource. 




Using ClassPathResource Implementation

As the name suggests it represents a resource being loaded from a classpath. One thing to note here is we can easily switch to java standard File or InputStream from Resource

For better understanding purposes, let’s create a simple Java project to demonstrate it with an example.

1) We created a simple text file that holds companies' names as following

Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions, Apple, AWS, bitspro

2) We created a simple Java class and spring boot REST API endpoint to demonstrate it. (Note: there is no need to have a REST endpoint for it. But for the sake of simplicity we are using Spring Boot) 


public static void main(String[] args) throws IOException {

    Resource companyDataResource = new ClassPathResource("companies.txt");

    File file  = companyDataResource.getFile();


    System.out.println("Filename: " + file.getName());

    System.out.println("Executable: " + file.canExecute());

    System.out.println("Readable: " + file.canRead());



    String content = new String(Files.readAllBytes(file.toPath()));

    System.out.println(content);

}

Output

> Task:Demo.main()

Filename: companies.txt

Executable: false

Readable: true

Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions, 
Apple, AWS, bitspro.


As you can see we can read the content of our file companies.txt with the help of ClassPathResource. But one has to keep in mind that ClassPathResource requires an absolute path. But in case you want to use a relative path you can pass a second argument as a class name. The given path should be relative to the class.

new ClassPathResource("../../data/students.txt", Students.class).getFile();

In the above example, the path to the employee's file is relative to the Student's class. 


3. Using Spring @Value annotation

Using the @Value annotation, we can inject a classpath resource directly into a Spring bean. One thing to note here is it loads the file eagerly.

@Value(“classpath:../../data/students.txt”)

Resource resourceFile;

//Somewhere in the code

File file = resource.getFile();



4. Using ResourceLoader

There is another way one can load their resources using ResourceLoader. It is also helpful in case you want lazy loading. We can provide a fully qualified URL or file path "file:Directory:/folder1/folder2/folder3/students.txt" or "classpath:students.txt".

ResourceLoader also supports relative file paths such as "WEB-INF/students.txt".

@Autowired
ResourceLoader resourceLoader;
Resource res = resourceLoader.getResource("classpath:companies.txt");
File file = res.getFile();


5. Using Spring REST API

Here is another way to download and read file from the resource folder in Spring Boot. 


@RestController

@RequestMapping("/api/v1/resouces")

public class AppResources {



    @Autowired

    ResourceLoader resourceLoader;



    @RequestMapping("/resources")

    public ResponseEntity<?> getResourceInfo() throws IOException {


            Resource res = resourceLoader.getResource("classpath:companies.txt");

            String output = "";

            File file = res.getFile();



            output += "Filename: " + file.getName() + " \n  Executable: " 
    + file.canExecute() + "\n Readable: \" + file.canRead()";

            String content = new String(Files.readAllBytes(file.toPath()));

            System.out.println(content);

            return new ResponseEntity<>(content,HttpStatus.OK);

    }

}

Output

Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions,
Apple, AWS, bitspro.


It is designed to be used by objects that can return Resource instances. Since all application contexts provide the ResourceLoader interface, Resource instances may be retrieved from any application context. 


6. Using ResourceUtils

Here is another way to load or read files from the resource folder in Spring boot application using ResourceUtils class. 

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.nio.file.Files;

import java.util.concurrent.TimeUnit;



public class Demo {



    public static void main(String[] args) throws IOException {

        File file  = loadEmployeesWithSpringInternalClass();

        String content = new String(Files.readAllBytes(file.toPath()));

        System.out.println(content);



    }



    public static File loadEmployeesWithSpringInternalClass() 
            throws FileNotFoundException {

        return ResourceUtils.getFile(

                "classpath:companies.txt");

    }



}


Output

> Task :Demo.main()

Google, Facebook, Twitter, Samsung, Microsoft, Folio3, AvanzaSolutions, Apple, 
AWS, bitspro.


Conclusion

That's all about 5 ways to read a file from the resource folder in Spring boot application and Java. Thanks for staying with us, with this we reach the end of our article. In this brief blog, we examined several methods for utilizing Spring to access and read a resource via Resource Interface, ClassPathResource, @Value annotation, ResourceLoader, and ResourceUtils. In addition to learning these techniques, we also practice them by using examples. 

To practice, we built a simple text file called "companies.txt" containing the names of several firms in it. To read this data file, we applied each method separately. I sincerely hope that this simple presentation has helped you comprehend the subject matter. 

I also hope by now you will be in a position to face any challenge related to reading files using Spring Boot.  

Other Java and Spring Articles, Resources and Tutorials you may like to explore

Thanks for reading this article so far. If you like this Spring Boot tutorial then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.