11

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 
}
Akadisoft
  • 306
  • 1
  • 2
  • 13
  • 2
    I want to access files in classpath and not from a specific folder like C:\\resources. – Akadisoft Dec 12 '12 at 20:52
  • 1
    Perhaps you want this: http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory – nwaltham Dec 12 '12 at 20:55
  • You can reuse code for this (after small modification) http://stackoverflow.com/questions/176527/how-can-i-enumerate-all-classes-in-a-package-and-add-them-to-a-list – CAMOBAP Dec 12 '12 at 20:59

3 Answers3

10

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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
ramsinb
  • 1,985
  • 12
  • 17
  • Hi, I'm trying to use your answer. Can you help me with that: http://stackoverflow.com/questions/29430113/accessing-files-in-specific-folder-in-classpath-using-java-works-only-for-sing ? – pstrag Apr 03 '15 at 10:28
3

This SO thread discuss this technique in detail. Below is a useful Java method that list files from a given resource folder.

/**
   * List directory contents for a resource folder. Not recursive.
   * This is basically a brute-force implementation.
   * Works for regular files and also JARs.
   * 
   * @author Greg Briggs
   * @param clazz Any java class that lives in the same place as the resources you want.
   * @param path Should end with "/", but not start with one.
   * @return Just the name of each member item, not the full paths.
   * @throws URISyntaxException 
   * @throws IOException 
   */
  String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
      URL dirURL = clazz.getClassLoader().getResource(path);
      if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
      } 

      if (dirURL == null) {
        /* 
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        String me = clazz.getName().replace(".", "/")+".class";
        dirURL = clazz.getClassLoader().getResource(me);
      }

      if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
        while(entries.hasMoreElements()) {
          String name = entries.nextElement().getName();
          if (name.startsWith(path)) { //filter according to the path
            String entry = name.substring(path.length());
            int checkSubdir = entry.indexOf("/");
            if (checkSubdir >= 0) {
              // if it is a subdirectory, we just return the directory name
              entry = entry.substring(0, checkSubdir);
            }
            result.add(entry);
          }
        }
        return result.toArray(new String[result.size()]);
      } 

      throw new UnsupportedOperationException("Cannot list files for URL "+dirURL);
  }
Community
  • 1
  • 1
Viral Patel
  • 8,506
  • 3
  • 32
  • 29
0

I think thats what you want:

String currentDir = new java.io.File(".").toURI().toString();
// AClass = A class in this package
String pathToClass = AClass.class.getResource("/packagename).toString();
String packagePath = (pathToClass.substring(currentDir.length() - 2));

String file;
File folder = new File(packagePath);
File[] filesList= folder.listFiles(); 

for (int i = 0; i < filesList.length; i++) 
{
  if (filesList[i].isFile()) 
  {
    file = filesList[i].getName();
    if (file.endsWith(".txt") || file.endsWith(".TXT"))
    {
      // DO YOUR THING WITH file
    }
  }
}
Anton Hell
  • 53
  • 7