In this article, we are going to present several ways to read a file from the resources folder in Java. This article covers plain Java solutions and methods dedicated to Spring applications.
2. Read a file from resources using
The most popular solution to read files from the resources folder is to use getResourceAsStream(...) method available in the
Let's demonstrate how this solution works using sample Java project with the following structure:
example.txt file, placed in
/src/main/resources folder, has the following content:
Main Java class that reads
example.txt file from the
resources folder has the following structure:
In this example we used
getClassLoader().getResourceAsStream(...) method available in
Class object to load file from resources into byte-based stream.
InputStream we used one of the available methods to convert InputStream to String in Java
3. Reading a file from resources folder using
In the next approach, we used getResource(...) method that returns the URL object for reading the resource, or null if the resource could not be found.
In this example we make a use of
getClassLoader().getResource(...) method to get
URL of our
example.txt file locate in
resources folder. Then we used
getFile(...) method to convert
You have many options to read a file in Java. In this example we used
Files.readAllBytes(...) method that simply convert
String in a one line.
4. Read a file from resources in the
Spring project using
ResourceUtils class comes with utility methods for resolving resource locations to files. We can use it to get a file from the resources folder in Spring applications.
In this example we will use Spring project with the following structure:
Spring boot main class contains a simple REST controller that will return the content of
example.txt file from available in the
The application runs on default port 8080. When you enter
http://location:8080 address in your browser you will see the content of the
In this tutorial, we presented several ways to get a file from the resources folder in Java. In Spring applications we have dedicated utility class that will do all the job for us. In plain Java we need to use
getResource(...) method. In many situations, we want to read the file and process it so the natural way is to use the
getResourceAsStream(...) approach that returns byte-based stream we can process right away.