Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a file from resource folder?

Tags:

java

file

maven

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.

like image 897
codereviewanskquestions Avatar asked Apr 01 '13 18:04

codereviewanskquestions


People also ask

How do I read a file from SRC main resources?

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.

How do I view the resources folder in a jar file?

This works when running inside and outside of a Jar file. PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver(); Resource[] resources = r. getResources("/myfolder/*"); Then you can access the data using getInputStream and the filename from getFilename .


2 Answers

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: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.java src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java src\main\resources\test.csv
// java.net.URL URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class); Path path = Paths.get(url.toURI()); List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); 
// java.io.InputStream InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class); InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(streamReader); for (String line; (line = reader.readLine()) != null;) {     // Process line } 

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.
like image 57
Paul Vargas Avatar answered Sep 18 '22 15:09

Paul Vargas


Try:

InputStream is = MyTest.class.getResourceAsStream("/test.csv"); 

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

like image 45
vanza Avatar answered Sep 20 '22 15:09

vanza