LCYSoft LCYSoft - 4 months ago 13
Java Question

How do I load a file from resource folder?

My project has 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 had this code but didn't work. I 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 dosen't work. It returns null. I am using Maven to build my project.

Thanks in advance.

Answer

Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil (code here).