How to get file from resources folder java
How to get file from resources folder java
Reading a File from Resources Directory
Last Updated: April 11, 2022
Learn to read a file from the resources folder in a Java application. We will learn to read the file present inside the jar file; and outside the Jar file as well.
A file outside the jar file may be present as a war file or an Eclipse project in the development environment.
1. Packaging a File into resources Folder
The resources folder belongs to the maven project structure where we place the configuration and data files related to the application. The location of the folder is “ src/main/resources “.
In the given examples, we are reading two files present in the resources folder. The first file demo.txt is at the root of resources folder. The second file data/demo.txt folder is inside a nested folder data in the resources folder.
2.1. ClassLoader.getResourceAsStream()
Use the getResourceAsStream() method to get the InputStream when reading a file from inside a jar file. Always use this method on the ClassLoader instance.
2.2. Complete Example
Once we have the InputStream reference, we can use it to read the file content or pass it to any resource handler class.
2.3. How to test the code
To test the above code, package the application as jar file using mvn clean package command. Also, provide the mainClass attribute to maven-jar-plugin and set its value to the class which has main() method and the test code.
Now, run the main() method from the console.
3.1. ClassLoader.getResource()
Use the getResource() method to get the File instance when reading a file from inside a war file. I suggest using this method on the ClassLoader instance.
3.2. Complete Example
Now use the File reference to read the file content.
3.3. How to test the code
To test the above code, package the application as a war file using mvn clean package command. Use the maven-resources-plugin plugin to copy the files from the resources folder to the root of the war file archive.
Now, run the main method from the console. Do not forget to add the classes to the classpath.
Read a File from Resources Folder in Java
This tutorial illustrates How to read a file from Classpath or Resources Folder in Java with practical examples using File IO, NIO, and FileChannel.
Overview
In the next sections we will explain how to read a file which is placed src/main/resources (Resources) directory. There are many ways to read a file from Classpath in Java. They are based on Java File IO, Java NIO, and Java File Channels. We will cover all of them one in this tutorial.
Using Java getResourceAsStream()
This is an example of using getResourceAsStream method to read a file from src/main/resources directory.
First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream. Then, we wrap the input stream reader into a BufferedReader instance.
The lines method on the BufferedReader class returns a Stream of Strings which are lazily read from the file. We are then printing each line from the file on the console.
Note that, in Java File IO we need explicitly close all of the streams and readers that we create. Also, the Java 8 Streams which are generated from File IO resources need to be closed. To do that, we are using a try-with-resources block to instantiate them.
Alternatively, we can use getResourceAsStream on the class loader.
The difference between the two is that when we use getResourceAsStream on the class the path is relative to current directory. Thus, we added a slash (/) to the path. On the other hand getResourceAsStream on the class loader instance takes absolute path. Which is why we have not added the slash (/).
Using FileReader
We can use BufferedReader by wrapping a FileReader to read contents of a file. Next, is an example of using BufferedReader to read file from Classpath.
Here we are creating an instance of FileReader by providing the path to file. Next, we create an Instance of BufferedReader upon the file reader. Finally, as seen in the previous example we create a Stream of lines from the buffered reader to print them on the console.
Using Files.newBufferedReader()
Next is how to use Files.newBufferedReader to read a file from resources directory. It is useful when we want to read files of large size.
Using Files.lines()
The Java Files class provides lines() method, which is one more handy abstraction to avoid the boilerplate code. Next is an example of how to read a Classpath resource line by line. Note that we are also providing UTF-8 Charset.
The try-with-catch resource block ensures that the respective streams are closed when the block ends.
Using DataInputStream
Next, we will cover an example of using DataInputStream to read data from a file in src/main/resources directory. The DataInputStream is useful for reading primitive java data types from a file.
Using FileChannel
Finally, we will see an example of using FileChannel to read file in resources directory. This is the fasted way of reading data from a file, especially when we are dealing with large files.
First, we create a Path from the resource file, and use it to instantiate a RandomAccessFile. The RandomAccessFile then provides the FileChannel.
Summary
In this detailed tutorial we have covered different ways of reading a file from src/main/resources folder in plain Java. We leaned that we can use current Class or a ClassLoader to read the file from resources folder as a Stream.
Also, we learnt a different ways of reading data from the file, along with examples of Java NIO and FileChannel abstractions. We also, learned it is important to close all of the File IO Streams and readers and we can use try-with-resources block to do that automatically. For more on Java, Please visit: Java Tutorials.
How to Read a File from Resources Folder in Java
1. Introduction
When you build a java project and pack it into a jar (or a war), the files under the resources folder are included into the jar. These files may include configuration files, scripts and other resources needed during run time. When the software is executed, it may need to load the contents of these files for some kind of processing — may be properties, sql statements, etc. In this article, we show you how to load these resources when the program is running.
2. Packaging Resources
Check out the directory hierarchy below:
Maven packs all the files and folders under main/resources into the jar file at the the root. You can access these files and folders from your java code as shown below.
3. Loading the Resources
The following code snippet shows how to load resources packed thus into the jar or war file:
Using the method Class.getResourceAsStream(String), you can get an InputStream to read the resource. The method returns null if the resource cannot be found or loaded.
To read binary resources, you can use directly use the InputStream instance. For reading a text resource, you can convert it to a Reader instance, possibly specifying the character encoding:
4. Using Absolute Path of Resource
To load a resource whose full path from the root of the jar file is known, use the full path starting with a “ / “.
How do I load a file from resource folder?
My project has the following structure:
I have a file in /src/test/resources/test.csv and I want to load the file from a unit test in /src/test/java/MyTest.java
I have this code which didn’t work. It complains «No such file or directory».
I also tried this
21 Answers 21
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Here are some examples of how that class is used:
IIRC getResourceAsStream() by default is relative to the class’s package.
As @Terran noted, don’t forget to add the / at the starting of the filename
Try following codes on Spring project
Or on non spring project
Here is one quick solution with the use of Guava:
Non spring project:
For spring projects, you can also use one line code to get any file under resources folder:
For java after 1.7
Alternatively you can use Spring utils if you are in Spring echosystem
To get to more behind the scene, check out following blog
The file was not found by a class loader, which means it was not packed into the artifact (jar). You need to build the project. For example, with maven:
So the files you added to resources folder will get into maven build and become available to the application.
I would like to keep my answer: it does not explain how to read a file (other answers do explain that), it answers why InputStream or resource was null. Similar answer is here.
If you use context ClassLoader to find a resource then definitely it will cost application performance.
Now I am illustrating the source code for reading a font from maven created resources directory,
It worked for me and hope that the entire source code will also help you, Enjoy!
Import the following:
The following method returns a file in an ArrayList of Strings:
getResource() was working fine with the resources files placed in src/main/resources only. To get a file which is at the path other than src/main/resources say src/test/java you need to create it exlicitly.
the following example may help you
You can use the com.google.common.io.Resources.getResource to read the url of file and then get the file content using java.nio.file.Files to read the content of file.
if you are loading file in static method then ClassLoader classLoader = getClass().getClassLoader(); this might give you an error.
You can try this e.g. file you want to load from resources is resources >> Images >> Test.gif
To read the files from src/resources folder then try this :
in case of non static reference:
My file in the test folder could not be found even though I followed the answers. It got resolved by rebuilding the project. It seems IntelliJ did not recognize the new file automatically. Pretty nasty to find out.
I got it work on both running jar and in IDE by writing as
This worked pretty fine for me :
I get it to work without any reference to «class» or «ClassLoader».
Let’s say we have three scenarios with the location of the file ‘example.file’ and your working directory (where your app executes) is home/mydocuments/program/projects/myapp:
a)A sub folder descendant to the working directory: myapp/res/files/example.file
b)A sub folder not descendant to the working directory: projects/files/example.file
b2)Another sub folder not descendant to the working directory: program/files/example.file
c)A root folder: home/mydocuments/files/example.file (Linux; in Windows replace home/ with C:)
1) Get the right path: a) String path = «res/files/example.file»; b) String path = «../projects/files/example.file» b2) String path = «../../program/files/example.file» c) String path = «/home/mydocuments/files/example.file»
Basically, if it is a root folder, start the path name with a leading slash. If it is a sub folder, no slash must be before the path name. If the sub folder is not descendant to the working directory you have to cd to it using «../». This tells the system to go up one folder.
2) Create a File object by passing the right path:
1. Introduction
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 getResourceAsStream method
The most popular solution to read files from the resources folder is to use getResourceAsStream(. ) method available in the ClassLoader object.
Let’s demonstrate how this solution works using sample Java project with the following structure:
Our 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.
To print InputStream we used one of the available methods to convert InputStream to String in Java
3. Reading a file from resources folder using getResource method
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 URL into File object.
You have many options to read a file in Java. In this example we used Files.readAllBytes(. ) method that simply convert InputStream to String in a one line.
4. Read a file from resources in the Spring project using ResourceUtils
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 resources folder:
The application runs on default port 8080. When you enter http://location:8080 address in your browser you will see the content of the example.txt file.
5. Conclusion
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 getResourceAsStream(. ) or 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.