Reading files from SpringBoot resources folder

Reading files from a SpringBoot jar is something a little complex.

I had tried to read a file from springboot resources folder using java.io.File. This is the code:

And I got the FileNotFoundException :

Since there is no path like file:/data/www/htdocs/my-app/lib/my-app.jar!/BOOT-INF/class existed in my computer, I got the exception.

Usually we can use ClassPathResource or ResourceLoader to get files from SpringBoot classpath (the resources folder).

The code using ClassPathResource

And we can use ResourceLoader like this :

Please note that the path in two examples is different: we need to add the flag of ‘classpath:’ as prefix when we use ResourceLoader.

Though there is a method of getFile() in the Resource interface, it’s recommand never use it.

If we need to transfer a file, it’s better to transfer it as InputStream than as File instance.

End!

Leave a Reply

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