Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing files in specific folder in classpath using Java

Tags:

java

io

I want to read a bunch of text files in com.example.resources package. I can read a single file using the following code:

InputStream is = MyObject.class.getResourceAsStream("resources/file1.txt")
InputStreamReader sReader = new InputStreamReader(is);
BefferedReader bReader = new BufferedReader(sReader);
...

Is there a way to get the listing of file and then pass each element to getResourceAsStream?

EDIT: On ramsinb suggestion I changed my code as follow:

BufferedReader br = new BufferedReader(new InputStreamReader(MyObject.class.getResourceAsStream("resources")));
String fileName;
while((fileName = br.readLine()) != null){ 
   // access fileName 
}
like image 855
Akadisoft Avatar asked Dec 12 '12 20:12

Akadisoft


1 Answers

If you pass in a directory to the getResourceAsStream method then it will return a listing of files in the directory ( or at least a stream of it).

Thread.currentThread().getContextClassLoader().getResourceAsStream(...)

I purposely used the Thread to get the resource because it will ensure I get the parent class loader. This is important in a Java EE environment however probably not too much for your case.

like image 85
ramsinb Avatar answered Oct 06 '22 08:10

ramsinb