Spring – Read files from classpath

In this tutorial, we discuss several ways of reading a resource file from classpath in a Spring MVC application.

1- ClassPathResource

Using ClassPathResource class provided by Spring Core, you can read a resource file using both absolute and relative paths.

To read a resource file through an absolute path, simply use:

To read it through a relative path, pass your current class as a second parameter:

After that, you can use getFile() or getInputStream() to parse the content of the resource.

2- @Value

If your resource file is in a fixed location and you already know its path, you can define your resource as a class field and annotate it with @Value, so that it’s loaded at the startup of the application.

After that, you’re free to use resourceFile field wherever you want inside your class.

3- ResourceLoader

Another way of reading a resource file in a Spring MVC application is through ResourceLoader.

You can simply define the ResourceLoader as a class field:

And then use it in your method as the following:

After that, you can use getFile() or getInputStream() to parse the content of the resource.

4- ResourceUtils

Using ResourceUtils is not recommended by the Spring team as it’s only intended to be used internally in the Spring Core code.

However, it’s still an option and can do the job:

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar