Load a File From Classpath In Spring Boot

Load a File From Classpath In Spring Boot:-

In this post, we are going to check How to Load a File From Classpath In Spring Boot. Long back I was working on a very simple project.

I wanted to read a JSON file from the resources folder.src/main/resources Hence written a code something like this below.

Now, this code works completely fine once I run it using,mvn:spring-boot:run but as soon I’m building and packaging the application using maven and running it as simple executable jar I’m getting an exception. Let’s go ahead and find out the solution now.

1. Using InputStream:-

Let’s See How We can read the File.

We have seen How we can Load a File From Classpath In Spring Boot If the file is inside a jar.

2. Reading as a File:-

There is another way to load resources in spring boot. We are now going to check how we can load a file from classpath in spring boot if the file is present in the filesystem not inside a jar.

3. Reading Resource as ResourceLoader:-

ResourceLoader is used to loads resources from class-path as well as file system.

Now we can use resource.getInputStream() or resource.getFile() as required.

4. Using ResourceUtils:-

Load a file from classpath in spring boot using ResourceUtils resolves the given resource location to a,java.io.File i.e. to a file in the file system.It doesn’t check if the file exists or not.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *