My project has the following structure:
/src/main/java/
/src/main/resources/
/src/test/java/
/src/test/resources/
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".
BufferedReader br = new BufferedReader (new FileReader(test.csv))
I also tried this
InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv))
This also doesn't work. It returns null
. I am using Maven to build my project.
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!
The following class can be used to load a
resource
from theclasspath
and also receive a fitting error message in case there's a problem with the givenfilePath
.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:
3) You are now good to go:
Here is one quick solution with the use of Guava:
Usage:
I solved this problem by adding
/scr/main/resources
folder to myJava Build Path
Import the following:
The following method returns a file in an ArrayList of Strings: