Accessing files in specific folder in classpath using Java

io, java

Solution

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.

Problem

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 } ```

Original source

Related problems